Learning how to create and query a view

In this section, we will learn how to create a view when writing queries. To create a view, use the following syntax: 

CREATE VIEW nameofview AS
SELECT col1, col2, co1n
FROM tablename
WHERE condition;

Let's take a query and place it into a view with the following code: 

USE lahmansbaseballdb; 
CREATE VIEW playergameinfo AS
SELECT p.playerid, birthyear,
a.yearid, a.teamid,
G_defense AS defensegames,
H AS numberofhits
FROM appearances AS a
JOIN people AS p
ON p.playerid = a.playerid
JOIN batting AS b
ON a.playerid = b.playerid
AND a.yearid = b.yearid
AND a.teamid = b.teamid
WHERE b.yearid = 2017
AND H <> 0;

Once this view is created, you will be able to query data from the view, as shown in the following query: 

USE lahmansbaseballdb; 
SELECT * FROM playergameinfo;

The following screenshot shows the results of the previous query: 

You can also specify the columns you want to be returned from the view, as shown in the following query: 

USE lahmansbaseballdb; 
SELECT playerid, birthyear, yearid, teamid, defensegames
FROM playergameinfo
WHERE teamid = 'CHA'
ORDER BY defensegames DESC;

The previous query will give you the results shown in the following screenshot:

You can see that the previous query specifies the columns you want to be returned, as well as that it uses the WHERE and ORDER BY clauses. You can do this with a view in exactly the same way as you would with a regular query. 

You can see the views that are created in MySQL Workbench in the SCHEMAS panel for each database, right below the Tables listing:

If you don't see the view you just created listed under Views, then right-click Views and choose Refresh All

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.39.142