What is the purpose (or use case) for an outer join in SQL?

試著忘記壹切 提交于 2019-12-09 07:05:00

问题


Is an outer join only used for analysis by the developer? I'm having trouble finding a use case for why you would want to include data in two or more tables that is unrelated or does not "match" your select criteria.


回答1:


An example use case would be to produce a report that shows ALL customers and their purchases. That is, show even customers who have not purchased anything. If you do an ordinary join of customers and purchases, the report would show only those customers with at least one purchase.




回答2:


Here is a very good list of examples by none other than Jeff Atwood - A Visual Explanation of SQL Joins he shows a new representation visually of the SQL joins.




回答3:


The "doesn't match" case is useful for optional data. Something which is present for some rows, but not for others.




回答4:


The OUTER JOIN is intended to address the cases where you wish to select a set of records from a primary table, which may or may not have related records contained in a secondary table.

An INNER join would omit from the list any primary records not also represented in the secondary table. Any OUTER JOIN guarantees the visiblity of all qualified primary records.




回答5:


The difference between outer and inner joins is primarily that the outer joins retain each record from both the joined tables, whether the join predicate is matched or not. So a use case would need to revolve around knowing about "missing stuff", eg. customers who haven't made purchases, or members who have missing personal details.




回答6:


Perhaps you have a users table and an address table related to it, since your users may choose not to enter an address, or they may have several (shipping, street, postal, etc). If you wanted to list all your users, but also display addresses for those that have them, you'd have to use an outer join for the address table.




回答7:


Say you had two tables one for users and one for something like qualifications, you want to do a query that gets all users with their qualifications if they have any. In this case you would use an outer join to get all the users back and those with qualifications. An inner join would only give you the users who had a qualification.




回答8:


A great article about outer joins: Meet the experts: Terry Purcell on coding predicates in outer joins: A comparison of simple outer join constructs



来源:https://stackoverflow.com/questions/1101343/what-is-the-purpose-or-use-case-for-an-outer-join-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!