|
|
|
Custom Search
| |
|
| |
|
Using Self Joins to Combine Data from the Same Table When you join a table to itself on columns with common values, you can picture how each record is related to one another. This is known as self-join. Self-join is normally used to represent hierarchical relationship or tree structure in a table. In Northwind employees table, an employee has a manager who is also an employee. Every employee has a ReportsTo value which stores the EmployeeID of employee's manager. In employees table, EmployeeID is primary key and ReportsTo is foreign key which relates back to EmployeeID in the same table. So we can use ReportsTo and EmployeeID to join the employees table to itself and find out the manager for each employee. Practice #1: Use self-join for employees table. In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. Note that the SQL needs to end with semi-colon if you have multiple queries in the query window. Most of the queries in the tutorials need Northwind MySQL database, you can download the database script on this page. /*
Query result set - 8 rows returned: Practice #2: Use self-join for orders table. In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. Note that the SQL needs to end with semi-colon if you have multiple queries in the query window. Most of the queries in the tutorials need Northwind MySQL database, you can download the database script on this page. /*
Query result set - 2238 rows returned: Practice #3: Use self-join for orders table. In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. Note that the SQL needs to end with semi-colon if you have multiple queries in the query window. Most of the queries in the tutorials need Northwind MySQL database, you can download the database script on this page. /*
Query result set - 1119 rows returned: Other tutorials in this category 1. Using Inner Joins to Combine Data from Two Tables |
|
Copyright © 2013 GeeksEngine.com. All Rights Reserved. This website is hosted by LunarPages. No portion may be reproduced without my written permission. Software and hardware names mentioned on this site are registered trademarks of their respective companies. Should any right be infringed, it is totally unintentional. Drop me an email and I will promptly and gladly rectify it. |
| Home | Feedback | Terms of Use | Privacy Policy |