[英]How to select rows where the ID exists in one table, but not another?
I have 2 tables: 我有2张桌子:
1) An Order table (which has OrderNumber
as the Id) 1)订单表(以
OrderNumber
作为ID)
2) An Items table which can have multiple rows and also has an OrderNumber
column tying each row to the ord er row above. 2)一个Items表,该表可以具有多行,并且还具有一个
OrderNumber
列, OrderNumber
列将每一行与上面的ord er行绑定在一起。
Most orders have multiple rows in the Items table - but some do not and I need to pull a report of Orders with no associated Items rows. 大多数订单在Items表中有多行-但有些则没有,我需要提取没有关联的Items行的Orders的报告。
I could do this on 2 queries in my PHP but there is clearly a smarter way to do it in MySQL. 我可以在PHP中的2个查询上执行此操作,但是显然有一种更聪明的方法可以在MySQL中执行此操作。 I understand JOINS but usually that's when there IS data in both tables.
我了解JOINS,但通常是两个表中都有数据时。 How do I tackle this if there ISN'T a tie in both?
如果两者都不存在,我该如何解决?
I would use a LEFT OUTER JOIN or FULL OUTER JOIN, depending on what you need.. It would help if you post the 2 queries, or some sample data... 根据您的需要,我将使用LEFT OUTER JOIN或FULL OUTER JOIN。如果您发布2个查询或一些示例数据,这将有所帮助。
OUTER handles any data that isn't there OUTER处理所有不存在的数据
here is a link to help you out: http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html 这是一个可以帮助您的链接: http : //www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
假设您的Items
表主键是Items_Id
SELECT * FROM Orders LEFT JOIN Items USING ( `OrderNumber` ) where Items.Items_Id IS NULL
In addition to the ways listed above, I'd say that I'd use this structure: 除了上面列出的方法之外,我还说我将使用以下结构:
SELECT * FROM Order where not exists (SELECT NULL FROM Items where OrderNumber = Orders.OrderNumber);
You can also add an index on OrderNumber column in Items for better performance: 您还可以在Items的OrderNumber列上添加索引,以提高性能:
CREATE INDEX Idx_Items on Items (OrderNumber);
You could use a the NOT IN
phrase for the where clause. 您可以在where子句中使用
NOT IN
短语。 This would get Order records who's Id's aren't in the Items table. 这将获得“订单”表中没有ID的订单记录。
SELECT * FROM Order WHERE Id NOT IN (SELECT OrderNumber FROM Items)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.