0% found this document useful (0 votes)
31 views9 pages

Join

Uploaded by

abinayamohan0527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
31 views9 pages

Join

Uploaded by

abinayamohan0527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
JOIN doin 187 When the required data are in more than one table, related tables are joined using a join condition The join condition combines a row in one table with a row in anoth- trtable based on the same values in the common columns|in mast cases (but not al ways), the common columns are the primary key in one table and a foreign key in another In this section, you will be introduced to different types of joins based on ¢ the join condition used s Cartesian Proauct A Cartestan product results from a mulutable query that does not have a WHERE clause. The product operation joins each row in the first table with each row in the second table: The product normally results in an output with a large number of rows and is not very useful, Whenever retrieving data from more than one table, you must use one or more valid join conditions to avoid a Cartestan product! You would per- £ you were looking to find all possible form a Cartesian product operation only i combinations of rows from two tables. In Figure 7-1, you will see an example of faculty members are matched unconditionally. All the figure The last and first names are selected from # ‘a product in which all students and 1 resulting rows are not shown in he STUDENT, table and a [SQL> SELEET Last. First, Name 2 FROM student, faculty; FIRST 7 Multiple Tabs: Joins and sp 188 ~ ra, 1 There is n0 join condition ¢ FACULTY table. easieis selected slpelyace of two tables with m and n rows, men soe MEHR TUDENT table has 6 rows and the FACULTY ar mem rows ea If you ae Pe each staden a - hence the Fetity advisor's name, you would use a cond hisorher sae Idand the FACULTY table's pnmary re ST a table's forengt a — Id or oduct 1s covered in this section, but itis not a join. re ees join condition. In Oracle, you wall Perform rte rout by dot providing enough join conditions ithe SET aae aa product by ws join conditions ts one less than the number of table — inthe FROM clause fhere are four (pes onforstateg tam *) oo in 1, Equyjoin 2 Nonequijoin. 3. Outer join 4 Selfjoin Q . olumnA nevtle ote Equiji pe ‘The equijoin is a join with a join condition involving common coll imins from two tabi, Ifyou need to get information about a student from the STUDENT table and cons. sponding information about the faculty 'y advisor from the FACULTY table, you woud use the following syntax: SELECT columnnames FROM tablenames WHERE join conse columns from both tables separal ed by ‘Parated by commas, and the join cond that includes common columns from each table. The join not always) includes a foreign key column from. one table and th mary Key column from the other table. Suppose you fame. the student's first Phone number. You wo The column names include hames are all tables used sey tyld value ts same. The shows the result fro: In Figure 7.2 but faculty members tymember Collins ( Man equi YOu see that all students are picked Are picked based ‘on the Facultyld in. Facultyld = 333) is not selected because pt at (SQL> SELECT studenttast WW yt 2 faculty Name FACULTY, faculty. Phos STUDENT, ~~ 3 FROM student, faculty Sop Phone Teh ; 4. WHERE student Facultyld » faculty “ Or) ty Mlk facul | si? Mtyid | STUDENT Diaz, Jose Mobley 2 Tyler. Mickey Chang an Patel, Rajesh Jones sus ~ | Rickles, Deborah Chang e, 6 rows selected. SQl> Figure 7-2 Equijoin inthe STUDENT table. On the other hand, Chang (Facultyld = $55) s picked twice because tt appears twice as a value in the foreign key column of the STUDENT table. The Cartesian product, as mentioned earlier, is rarely useful, but ‘equijoin is a yer) important operation in database querying. Another thing to be noted is: the use of tablenamecoluninname. When columns are retnieved from more than ‘one table, be use of a table name qualifier in front of the column name tells Oracle to retrieve that column from the specified table Oracle is pretty smart about it If a column name exists in only One of the two tables involved in the que: yt 1s NOL Necessary to use a able name as a qualifier. If a column exists in both tables, you must use the table name qualifier The join condition in an equijoin will normally have the table name qualifier Because the join condition usually has the same colt ies from (wo tables, the column names become ambiguous without a qualifier The qualifier | «tually improves performance because you are telling the Oracle server where go to find that column, Remember that the two join columns need not have same name. Sometimes, the required information is in more than two tab the FROM clause will include all needed tables, and the WHERE more than one join condition. If you need to joi Jom conditions. In our NamanNavan (N2) Corporation database mographic information is in the EMPLOYEE table. The thee foreign keys; Positionld, referencing the POSITION ‘as the QUALIFICATION table, and Deptld, referencin; “ould need to join four tables to retrieve informatio means the query will have 4 — Chap.7 Multiple Tables: joing 4 160 hown in Figure 7.3 ok like the one 5! For The query cL join conditions. There is no limit on, ete, hree tables ust aay Liat ithin a query conditions W — “employee.tname Il mployee.Fname EMG) dept. position id = dept.Deptid = position.Positionid; DEPARTMENT POSITION i loa 3 FROM employee. JePk | WHERE employee.Dep | § AND employee.Positionld | Marke Mani Houston, Larry piesa) oat | nobers, and Infosys Programmer | McCall, Alex Infosys iM : peu Deeks sales Manager Shaw, Jinku sale Mansa | Garner, Stanley Finan chen, Sunny Accountant 8 rows selected. sQl> Figure 7-3 Multiple joins q ion from. tables usu The multiple-join example selects information from three tables using ge with two join conditions. If you look at the query, the table qualifiers are used ge: a few times. There is a Way to shorten and simplify this query. yin \or{ino\ ORR \ In Chapter 5, you learned about column Pro which are used fo headings in a query. Table aliases are used to avoid using length; and over again in a query. A table alias can be from 1 to 30 very short alias names are used to shorten the query and sat table alias appears in the FROM clause of the SELECT query. followed by a space, and then a table alias is supplied. Thoug SELECT clause, alias names can also be used as qualifiers fo SELECT clause. All table aliases are valid only in the SI are named and used. In Figure 7-4, you will see the query from results obtained from the queries in Figures 7-3 in Figure 7-4 is shortened by the use of table ali; Table Aliases Gqu> SELECT eLname I," eFrame EMPLOYEE d,DeptName DEPARTMENT, q.Qual 3 FROM employee e, dept d, qualification q Dese QUALIFICATION 4 WHERE e.Deptid = d.Deptid 5 AND e Qualld = 4.Qualld cot EMPLOYEE DEPARTMENT. QUAL smith, John Finance * Houston, Larry Marketing ees goberts, Sandi Finance Masa McCall, Alex Infosys Dey, Derek Infosys esiond Garner, Stanley Sales High | Chen, Sunny Finance Bachelors 7 rows selected. | sat> Figure 7-4 Table aliases EMPLOYEE table with the QUALIFICATION tables instead of the POSITION table. The result contains seven rows in Figure 7-4 instead of eight TOWs, as in Figur ecause one of the employees does not have a Qualld. Additional Conditions Inaddition fo join conditions, you may use additional conditions using the AND oper- aior {o restrict information. Suppose you want to see the information of Figure 7-4 for employees belonging to department number 10 only. Figure 7-5 shows the use of additional condition with the AND operator where the information is displayed for Depild = 10 only. The three tables are joined for employees in Department 10, which results in three rows instead of all eight employee rows. hn YHoes Nonequijoin There is no matching column in the EMPLEVEL table for the Salary. EMPLOYEE table. The only possible relationship between the two ‘ween the Salary column of the EMPLOYEE table and the LowS Salary columns in the EMPLEVEL table. The join condition for wntten using any operator other than the = operator. That is Squijoin. Figure 7-6 is an example of a nonequijoin. The nonequijoin condition of Figure 7-6 could have € Salary >= |,LowSalary AND e-Salary <= Chap. 7 Multiple Tabs: Jong 162 tname ll @Foame EMPLOYEE, {aopy seit eptName DEPARTMENT, 4 Qualbese QUAU - | ts pPosDesc POSITION MATION, 3 1 pom employes, deptd, qualification 4, poston » | f mere ¢.deptid = d.Deptid tion |g AND equalld = q.Qualld | 7 AND ePositionid = p.Positionid 8 AND e.Deptid = 10 Teena DEPARTMENT | employee Finance nurs me d Finance joberts, Sandi | Chen, Sunny Boance =. Figure 7-5 Additional condition with join, ["SQl> SELECT eLname II’,‘ll e.Fname EMPLOYEE, e Sala "Y, LLeveing 2. FROM employee e, emplevel | 3 WHERE e Salary BETWEEN |.LowSalary AND L.HighSalary at | EMPLOYEE SALARY | shaw, Garner, Stanley 45000 Chen, Sunny 35000 | Roberts, Sandi 75000 McCall, Alex 66500 Dev, Derek 80000 Smith, John 265000 Houston, Larry 150000 8 rows selected. SQ Figure 7-6 Nonequijoin If you look at the EMPLEVEL table, none of the salaries app level. In other words, there is no overlapping. None of the emple that is not included in the range of salaries, For these two appears once in the result. Note that none of the columns a aliases are not necessary (though they are used here in this ey 2 We 163 We yy 20 » Vy bp , > voea " { Lol) yay toto Can a ‘ from two tabl : join that the rows les are selected o) eu gues are the same in both tables. If a row in one tabl nly ifthe common va le it a ry the other table, it 1s not joined, Figure 7-2 dj does not have a ul f isp! sent StUDENT table and their advisors from the FACULTY tube gue ¢ Some ol gm ie abers are not any student's advisor, so they di wool a to see all those faculty advisor Dene eee st sre “{join condition and create a join known as an outer joint ange oot er she that does not contain the matching value as y pee case, the deficient table 1s the STUDENT table, because it does not faculty Dee uses she (+ ) sree in the joi Siac Cos side (You will see (soon in Figure 7-8, which co a te deficient ie tables.) The (+) operator can be fa Bee ee a and — any side of the joit it cannot be used on both sides in one condition. join euler join on t qnion, BU The general syntax is ( seLecr tablenamet.columnname, tablename2,columaname - FROM tablenamet, tablename2 WHERE tablenamet.columnname (+) = tablename2.columnname;\ The join condition will look different if the (+) operator is used on the right cde For example, vONAL \WHERE tablenameT.columnname = tablename2.columnname (+); figure 7-7 shows an outer join using the EMPLOYEE and QUALIFICATION tables The outer jon operator (+) is used on the QUALIFICATION side, because othe eu! “ownall f SQL> SELECT eFname |l’,“ll e.tname EMPLOYEE, q.QualDese 2 FROM employee e, qualification q | 3 WHERE e.Qualld = q.Qualld (+) al EMPLOYEE QUALDESC | mss etl Lary Houston Masters Sandi Roberts “Masters ‘Alex McCall Associates Derek Dev Doctorate Jinku Shaw a | Stanley Garner High School | Sunny Chen Bachelors Brows selected. SQ 164 first 8 sLast STUDENT, {Name ADVISOR | 3 FROM faculty f, student s 4) WHERE 5 Facultyld (+) = ffacultyid Sel | STUDENT ee SQL> SELECT 2 | najesh Patet | Jose Diaz | Amir Khan | Bran Lee | mickey Tyler | Deborah Rickles | 9 rows selected. | slo SELECT First 1° stast STUDENT, 2 {Name ADVISOR 32 FROM faculty f, student s 4 WHERE sFacultyid = {facultyld | Deborah Rickles | arian Lee Amir Khan Williams | | 6 rows selected | sQt> Figure 7-8 Comparing outputs from outer jou atts the deficient table or it generates a null value for table without any qualification value. The equijoin employees, but the outer join also includes one qualification Figure 7-8 compares outputs from outer join and e The equijoin returns six students with their faculty Outer join returns three extra rows with f. nam is used on the STUDENT table's side, because it ‘members with no match in the STUDENT table. ” 165 wt js joing @ able to itself. Tt sounds meani vy scenario’ In the EMPLOYEE table, ‘ shat describes each entity: For example, Employeetd 200 representson bal om sku The table also has another column called Supervisor, which a aployee supervisors. How can you find name of the Supervisor ‘eae ; Youcan look up the supervisor 1D. go to the Employeeld column Gant A vad then read the name. This ts easier said than done, however, A self-joi ew vin that is NOL SO EASY tO ae : Jos “yen a table 18 joined to itself, (Wo Copies of the sam ; nh mre treated like any Wo different tables, and a join eee = Sreiwocopies Let us explain that by using the EMPLOYEE table The folloving vvatwons are performed in the self-join of Figure 7.9: Se ngless, but think abo : Employeeld is the pinytt ye Ii ole! ps + Two copies of the EMPLOYEE table are created with the aliases ¢ ands. + Anemployee’s last name 1s picked from the e table, and the corresponding Supervisor ID 1s retrieved, + The matching Employeeld is found from the s table. The fi the etable does not have a supervisor and so is not picked, « The last name from the s table is retrieved based on the Employeeld irst employee in SQL> SELECT e.tname il’,"ll e.fname Employee, teat stname I‘,‘ll s.Fname Manager | | 3 FROM employee e, employee s 4 WHERE e.Supervisor = s.Employeeld; surest | EMPLOYEE Houston, Larry Smith, John Roberts, Sandi Smith, John McCall, Alex Dev, Derek Dev, Derek Smith, John Shaw, Jinku Garner, Stanley Garner, Stanley Smith, John Chen, Sunny Roberts, Sandi | 7#ows selected, | SQL> Figure 7-9 Self-join oshont, the tal “Sr The In; Self-join, ble 1s looked at twice, once for do-US (IU) College database Table COURSE contains a PreR ),Courseld. You will perform this sel

You might also like