Download presentation
Presentation is loading. Please wait.
1
A Bit More SQL CIT 381 2001 October 10
2
Mandatory Use of Aliases Consider the following schema Empl_numnameageRep_officemanager 105Bill3713104 Bob3312106 Sam5211NULL How do we determine the name of Bill’s manager?
3
Aliasing, cont’d SELECT s2.name FROM SALESREPS s1, SALESREPS s2 WHERE s1.name=‘Bob’ AND s1.manager=s2.empl_num; o Aliases must be used here. o The row referenced by s1 is intended to be Bob… o …while s2 will be his manager’s. o Remember, first FROM, then WHERE, then SELECT
4
Non-Standard ACCESS SELECT class_crn FROM student INNER JOIN enroll ON student.stud_ssn=enroll.stud_ssn WHERE student.stud_name=‘Alice’ o The ON clause supports the join condition o This has identical output to previous version oAllows for use of what are called outer joins
5
Another Join This lists the crn’s of each student (alphabetically) …for each student taking a class. Suppose we wanted to list the crn’s of each class taken by each student: SELECT s.stud_name, e.class_crn FROM student as s INNER JOIN enroll as e ON s.stud_num=e.stud_num ORDER BY 1;
6
Outer Joins –The words LEFT JOIN indicate that unmatched students (the table on the left) will also be listed – RIGHT JOIN another possibility –Other engines support a full outer join (left and right). If a student takes no classes and we want to list that student in the previous query, we need an outer join SELECT s.stud_name, e.class_crn FROM student as s LEFT JOIN enroll as e ON s.stud_num=e.stud_num ORDER BY 1;
7
Example Outer Join SELECT s1.name AS EmpName, s2.name AS ManagName FROM salesreps s1 LEFT JOIN salesreps s2 ON s1.manager = s2.empl_num ORDER BY s1.name; List the names of all employees and the names of their managers, including those employees who have no managers.
8
EmpNameManagName Bill AdamsBob Smith Sam Clark Dan RobertsBob Smith Larry FitchSam Clark Mary JonesSam Clark Nancy AngelliLarry Fitch Paul CruzBob Smith Sam Clark Sue SmithLarry Fitch Tom SnyderDan Roberts
9
Outer Joins in SQL Text LEFT JOIN indicated by *=, as in SELECT s.stud_name, c.class_crn FROM student as s, enroll as e WHERE s.stud_num * = e.stud_num ORDER BY 1; Join notation very non-standard across products Informix: FROM enroll, OUTER student
10
Unions Can “merge” together the results of two queries SELECT stud_ssn FROM student WHERE stud_address=‘Agate St.’ UNION SELECT s.stud_ssn FROM student s, enroll e WHERE s.stud_ssn=e.stud.ssn AND e.class_crn=14782; This finds students who live on Agate street or who have taken class 14782. The fields in the SELECT clause must have the same name and be the same type.
11
UNION ALL UNION of two sets removes duplicates UNION ALL retains the duplicates Why retain duplicates? Who knows – you may want to count them FUTURE TOPIC: How to count.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.