Sql 加入时过滤数据
我有两个表,我想在两个表连接在一起之前过滤两个表中的数据 客户表:Sql 加入时过滤数据,sql,sql-server,database,where-clause,Sql,Sql Server,Database,Where Clause,我有两个表,我想在两个表连接在一起之前过滤两个表中的数据 客户表: ╔══════════╦═══════╗ ║ Customer ║ Year ║ ╠══════════╬═══════╣ ║ A ║ 2018 ║ ║ B ║ 2019 ║ ║ C ║ 2020 ║ ╚══════════╩═══════╝ 条目表: ╔══════════╦═══════╦══════════╗ ║ Cu
╔══════════╦═══════╗
║ Customer ║ Year ║
╠══════════╬═══════╣
║ A ║ 2018 ║
║ B ║ 2019 ║
║ C ║ 2020 ║
╚══════════╩═══════╝
条目表:
╔══════════╦═══════╦══════════╗
║ Customer ║ Entry ║ Category ║
╠══════════╬═══════╬══════════╣
║ A ║ 5575 ║ D ║
║ A ║ 6532 ║ C ║
║ A ║ 3215 ║ D ║
║ A ║ 5645 ║ M ║
║ B ║ 3331 ║ A ║
║ B ║ 4445 ║ D ║
╚══════════╩═══════╩══════════╝
我想离开加入,所以我从Customer表中获取2019年和2020年的所有记录。此外,我想在加入之前在entry表中筛选类别D
预期结果:
╔══════════╦═══════╦═══════╗
║ Customer ║ Year ║ Entry ║
╠══════════╬═══════╬═══════╣
║ ║ ║ ║
║ ║ ║ ║
║ B ║ 2019 ║ 4445 ║
║ C ║ 2020 ║ NULL ║
╚══════════╩═══════╩═══════╝
如果我要执行以下查询:
选择Customer.Customer,Customer.Year,Entry.Entry
来自客户
左连接条目
ON Customer.Customer=Entry.Customer
其中customer.year in'2019'、'2020'和Entry.Category='D'
此外,还可以使用下面的查询完成
选择Customer.Customer,Customer.Year,Entry.Entry
从“2019年”和“2020年”的客户中选择*
左连接选择*自条目,其中Category='D'条目
ON Customer.Customer=Entry.Customer
哪个查询会更优化、更快
谢谢你的帮助 您似乎希望在ON子句和WHERE子句中都进行筛选: 请注意,如果年份是一个数字,则在in值中删除单引号
作为一般规则,左联接中第一个表上的筛选器位于WHERE子句中。后续表上的过滤器位于on子句上。对于类似的问题,最好检查两个查询的查询执行计划并进行比较。对于SQL Server,您可以使用选项在Management Studio中创建。
SELECT c.Customer, c.Year, e.Entry
FROM Customer c LEFT JOIN
Entry e
ON c.Customer = e.Customer AND e.Category = 'D'
WHERE c.year in ('2019', '2020');