SQL 应用左连接前过滤表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15077053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter Table Before Applying Left Join
提问by Tom Jenkin
I have 2 tables, I want to filter the 1 table beforethe 2 tables are joined together.
我有 2 个表,我想在 2 个表连接在一起之前过滤 1 个表。
Customer Table:
客户表:
╔══════════╦═══════╗
║ Customer ║ State ║
╠══════════╬═══════╣
║ A ║ S ║
║ B ║ V ║
║ C ║ L ║
╚══════════╩═══════╝
Entry Table:
条目表:
╔══════════╦═══════╦══════════╗
║ Customer ║ Entry ║ Category ║
╠══════════╬═══════╬══════════╣
║ A ║ 5575 ║ D ║
║ A ║ 6532 ║ C ║
║ A ║ 3215 ║ D ║
║ A ║ 5645 ║ M ║
║ B ║ 3331 ║ A ║
║ B ║ 4445 ║ D ║
╚══════════╩═══════╩══════════╝
I want to Left Join so I get all records from the Customer table regardless of whether there are related records in the Entry table. However I want to filter on category D in the entry table before the join.
我想Left Join,所以我从Customer 表中获取所有记录,而不管Entry 表中是否有相关记录。但是我想在 join 之前过滤条目表中的类别 D 。
Desired Results:
预期结果:
╔══════════╦═══════╦═══════╗
║ Customer ║ State ║ Entry ║
╠══════════╬═══════╬═══════╣
║ A ║ S ║ 5575 ║
║ A ║ S ║ 3215 ║
║ B ║ V ║ 4445 ║
║ C ║ L ║ NULL ║
╚══════════╩═══════╩═══════╝
If I was to do the following query:
如果我要执行以下查询:
SELECT Customer.Customer, Customer.State, Entry.Entry
FROM Customer
LEFT JOIN Entry
ON Customer.Customer=Entry.Customer
WHERE Entry.Category='D'
This would filter out the last record.
这将过滤掉最后一条记录。
So I want all rows from the left table and join it to the entry table filtered on category D.
所以我想要左表中的所有行并将其连接到按类别 D 过滤的条目表中。
Thanks to any help in advance!!
提前感谢任何帮助!!
回答by Taryn
You need to move the WHERE
filter to the JOIN
condition:
您需要将WHERE
过滤器移动到JOIN
条件:
SELECT c.Customer, c.State, e.Entry
FROM Customer c
LEFT JOIN Entry e
ON c.Customer=e.Customer
AND e.Category='D'
回答by Jeff Rosenberg
回答by c z
Or...
或者...
SELECT c.Customer, c.State, e.Entry
FROM Customer c
LEFT JOIN Entry e
ON c.Customer=e.Customer
WHERE e.Category IS NULL or e.Category='D'