应用左连接之前的过滤表

时间:2013-02-25 21:43:01

标签: sql join filter where

我有2个表格,我想在<2>表连接在一起之前过滤1个表

客户表:

    ╔══════════╦═══════╗
    ║ Customer ║ State ║
    ╠══════════╬═══════╣
    ║ A        ║ S     ║
    ║ B        ║ V     ║
    ║ C        ║ L     ║
    ╚══════════╩═══════╝

条目表:

   ╔══════════╦═══════╦══════════╗
   ║ Customer ║ Entry ║ Category ║
   ╠══════════╬═══════╬══════════╣
   ║ A        ║  5575 ║ D        ║
   ║ A        ║  6532 ║ C        ║
   ║ A        ║  3215 ║ D        ║
   ║ A        ║  5645 ║ M        ║
   ║ B        ║  3331 ║ A        ║
   ║ B        ║  4445 ║ D        ║
   ╚══════════╩═══════╩══════════╝

好的我想要左连接,所以我从Customer表中获取所有记录,无论Entry表中是否有相关记录。但是,我想在加入之前的条目表中过滤类别D.

期望的结果:

   ╔══════════╦═══════╦═══════╗
   ║ Customer ║ State ║ Entry ║
   ╠══════════╬═══════╬═══════╣
   ║ A        ║ S     ║  5575 ║
   ║ A        ║ S     ║  3215 ║
   ║ B        ║ A     ║  4445 ║
   ║ C        ║ L     ║  NULL ║
   ╚══════════╩═══════╩═══════╝

如果我要进行以下查询:

   SELECT Customer.Customer, Customer.State, Entry.Entry
   FROM Customer
   LEFT JOIN Entry
   ON Customer.Customer=Entry.Customer
   WHERE Entry.Category='D'

这将过滤掉最后一条记录。

所以我想要左表中的所有行,并将它连接到在类别D上过滤的条目表。

感谢提前帮助!!

3 个答案:

答案 0 :(得分:81)

您需要将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'

请参阅SQL Fiddle with Demo

答案 1 :(得分:18)

你也可以这样做:

SELECT c.Customer, c.State, e.Entry
FROM Customer AS c
LEFT JOIN (SELECT * FROM Entry WHERE Category='D') AS e
ON c.Customer=e.Customer

SQL小提琴here

答案 2 :(得分:0)

或者...

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'