Language SQL SQL Adv Reference: W3School - http://www.w3schools.com/sql/default.asp http://www.tomjewett.com/dbdesign/dbdesign.php?page=recursive.php Recursive Associations/Relationship A recursive association connects a single table(serving in one role) to itself (serving in another role). Example: In most companies, each employee (except the CEO) is supervised by one manager. Of course, not all employees are managers. This example is used in almost every database textbook, since the association between employees and managers is relatively easy to understand. Perhaps the best way to visualize it is to start with two tables. 1
Recursive Associations/Relationship Incorrect Model The problem with this model is that each manager is also an employee. Building the second (manager) table not only duplicates information from the employee table, it virtually guarantees that there will be mistakes and conflicts in the data. We can fix the problem by eliminating the redundant class and re-drawing the association line. Recursive Associations/Relationship Correct model Normally, we wouldn t show an fk in the class diagram; however, including the manager as an attribute of the employee here (in addition to the association line) can help in understanding the model. In the relation scheme, we can explicitly show the connection between the surrogate pk (employeeid) and the managerid (which is an fk, even though it is in the same scheme). 2
Recursive Associations/Relationship How its looks in a data table Retrieving data from a Recursive Association To produce a list of employees and their managers, we have to join the employees table to itself, using two different aliases for the table name. An outer join is needed to include any employee who is not managed by anyone. SELECT E.lastName AS Employee, M.lastName AS Manager FROM Employees E LEFT OUTER JOIN Employees M ON E.managerID = M.employeeID ORDER BY E.lastName 3
Retrieving data from a Recursive Association In effect, the SQL statement works as if there were two copies of the employees table, as in the first (incorrect) UML diagram. You can visualize rows being joined this way: Disable Foreign Keys To disable all foreign Keys SET FOREIGN_KEY_CHECKS = 0; To enable all foreign Keys SET FOREIGN_KEY_CHECKS = 1; 4
Subqueries Sometimes you don t have enough information available when you design a query to determine which rows you want. In this case, you ll have to find the required information with a subquery. Example: Find the list of buildings that are in Montreal (should use the name Montreal not the Id). We might start writing this query as we would any of the ones that we have already done: SELECT * FROM building WHERE buildingcityid =??; Subqueries We don t know what buildingcityid to put in the WHERE clause. No, we can t look it up manually and type it into the query we have to find the answer based only on the information that we have been given! Fortunately, we also know how to find the cityid by writing another query: SELECT cityid WHERE cityname= 'Montreal'; Notice that this query returns a single column and a single row 5
Subqueries Syntactically, all we have to do is to enclose the subquery in parenthses, in the same place where we would normally use a constant in the WHERE clause. We ll include the cityid in the SELECT line to verify that the answer is what we want: SELECT cityid WHERE cityname= ( SELECT cityid WHERE cityname= Montreal ); Exercises 1. Using a subquery write a query to display all buildings in Montreal ; 2. Using a subquery write a query to display all Buildings in Montreal and Laval ; 3. Using a subquery write a query to display all cities in Canada ; 4. Using a subquery write a query to increase the rent price in 10% for all apartments in Montreal; 6
Answer 1) SELECT * FROM building WHERE buildingcityid=(select cityid WHERE cityname='montreal'); 2) SELECT * FROM building WHERE buildingcityid IN (SELECT cityid WHERE cityname IN ('Montreal, Laval'); 3) SELECT * WHERE citycountryid = (SELECT countryid FROM country WHERE countryname = 'Canada'); Answer 4) UPDATE apartment SET apartmentrentprice = (apartmentrentprice*1.1) WHERE apartmentbuildingid IN (SELECT buildingid FROM buildinginner INNER JOIN city ON (buildingcityid = cityid) WHERE cityname = 'Montreal'); 7
Views A view is simply any SELECT query that has been given a name and saved in the database. For this reason, a view is sometimes called a named query or a stored query. To create a view, you use the SQL syntax: CREATE OR REPLACE VIEW <view_name> AS SELECT <any valid select query>; Views The view query itself is saved in the database, but it is not actually run until it is called with another SELECT statement. For this reason, the view does not take up any disk space for data storage, and it does not create any redundant copies of data that is already stored in the tables that it references The keywords OR REPLACE in the syntax shown above are optional. Although you don t need to use them the first time that you create a view, including them will overwrite an older version of the view with your latest one, without giving you an error message. The syntax to remove a view from your schema is exactly what you would expect: DROP VIEW <view_name> 8
Using Views A view name may be used in exactly the same way as a table name in any SELECT query. Once stored, the view can be used again and again, rather than re-writing the same query many times. The most basic use of a view would be to simply SELECT * from it, but it also might represent a pre-written subquery or a simplified way to write part of a FROM clause. In many systems, views are stored in a pre-compiled form. This might save some execution time for the query, but usually not enough for a human user to notice. One of the most important uses of views is in large multi-user systems, where they make it easy to control access to data for different types of users. As a very simple example, suppose that you have a table of employee information on the scheme Employees = {employeeid, empfname, emplname, empphone, jobtitle, payrate, managerid}. Obviously, you can t let everyone in the company look at all of this information, let alone make changes to it. Your database administrator (DBA) can define roles to represent different groups of users, and then grant membership in one or more roles to any specific user account (schema). In turn, you can grant table-level or view-level permissions to a role as well as to a specific user. Suppose that the DBA has created the roles managers and payroll for people who occupy those positions. In Oracle, there is also a pre-defined role named public, which means every user of the database Exercises 1. Create a view to produce a list with the contract number, tenant name, contract rent price, building address and city name; 2. Using the view that you created before dispaly all datas; 3. Using the view that you created before display all columns for the registers that the contract rent price is bigger than 1000.00 and lower than 1200.00; 9
Answer 1) CREATE VIEW apartlist AS SELECT contractid, contractrentprice, tenantname, buildingaddress, cityname FROM apartment apartment INNER JOIN building building ON apartmentbuildingid = buildingid INNER JOIN contract ON contracapartmentnumber = apartmentnumber AND contracapartmentbuildingid = apartmentbuildingid INNER JOIN tenant tenant ON contractenantid = tenantid INNER JOIN city ON buildingcityid = cityid; 2) SELECT * FROM apartlist; 3) SELECT * FROM apartlist WHERE contractrentprice BETWEEN 1000 AND 1200; 10