简体   繁体   中英

Need help in understanding JOINS in SQL

I was asked the below SQL question in an interview. Kindly explain how it works and what join it is.

Q: There are two tables: table emp contains 10 rows and table department contains 12 rows.

 Select * from emp,department;

What is the result and what join it is?

It would return the Cartesian Product of the two tables, meaning that every combination of emp and department would be included in the result.

I believe that the next question would be: Blockquote

How do you show the correct department for each employee?

That is, show only the combination of emp and department where the employee belongs to the department.

This can be done by:

SELECT * FROM emp LEFT JOIN department ON emp.department_id=department.id;

Assuming that emp has a field called department_id , and department has a matching id field (This is quite standard in these type of questions).

The LEFT JOIN means that all items from the left side ( emp ) will be included, and each employee will be matched with the corresponding department. If no matching department is found, the resulting fields from departments will remain empty. Note that exactly 10 rows will be returned.

To show only the employees with valid department IDs, use JOIN instead of LEFT JOIN . This query will return 0 to 10 rows, depending on the number of matching department ids.

The join you specified is a cross join . It will produce one row for each combination of records in the tables being joined.

I'll let you do the math from there.

This will do a cross join I believe, returning 120 rows. One row for each pair-wise combination of rows from each of the two tables.

All-in-all a fairly useless join most of the time.

You will get all rows from both tables with each row joined together.

This is known as a Cartesian join and is very bad.

You will get a total of 120 rows.

This is also the old implied syntax (18 yeasr out of date) and accidental cross joins are a common problem with this syntax. One should never use it. Explict joins are a better choice. I would have also mentioned this in an interview and explained why. I also would not have taken the job if they actually used crappy syntax like this because it's very use shows me the database is very likely to be poorly designed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM