应用左连接之前过滤表
我有 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 ║
╚══════════╩═══════╩══════════╝
我想要左连接,这样无论条目表中是否有相关记录,我都会从客户表中获取所有记录。但是,我想在连接之前过滤条目表中的类别 D。
期望的结果:
╔══════════╦═══════╦═══════╗
║ Customer ║ State ║ Entry ║
╠══════════╬═══════╬═══════╣
║ A ║ S ║ 5575 ║
║ A ║ S ║ 3215 ║
║ B ║ V ║ 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 过滤的条目表中。
提前感谢任何帮助!
I have 2 tables, I want to filter the 1 table before the 2 tables are joined together.
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.
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.
Thanks to any help in advance!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将
WHERE
过滤器移至JOIN
条件:请参阅 SQL摆弄演示
You need to move the
WHERE
filter to theJOIN
condition:See SQL Fiddle with Demo
您还可以执行以下操作:
SQL Fiddle 此处
You could also do:
SQL Fiddle here
或者...
Or...
如果您使用 PostgreSQL,我认为您还可以使用 WITH 子句来创建
通用表表达式。如果您要在同一查询的其他公共表表达式中使用此表,这将特别有用。
例子:
If you are using PostgreSQL i think that you can also use WITH clause to create
Common Table Expression. This will especially be helpful if you are going to use this table in other Common Table Expressions in the same query.
Example: