SQL联接,其中两个参数必须在表中
我使用的是MS SQL Server 2014,其中一个表如下所示:(表1) 另一张桌子是这样的:(表2) 我想从第一个具有过滤器1和2的表中获取所有属性(在本例中,仅获取PropertyId 1) 我可以使用以下方法进行此操作:SQL联接,其中两个参数必须在表中,sql,sql-server,Sql,Sql Server,我使用的是MS SQL Server 2014,其中一个表如下所示:(表1) 另一张桌子是这样的:(表2) 我想从第一个具有过滤器1和2的表中获取所有属性(在本例中,仅获取PropertyId 1) 我可以使用以下方法进行此操作: Select * from table1 where id in (select PropertyId from table2 where filter = 1) AND (select PropertyId from table2 where filter = 2)
Select * from table1 where id in (select PropertyId from table2 where filter = 1) AND (select PropertyId from table2 where filter = 2)
如果我使用join,我将获得表2中的所有属性:
Select * from table1 join table2 on table1.PropertyId = table2.PropertyId where table2.Filter in (1,2)
表1大约有20万行,表2大约有250万行,所以解决方案必须非常有效:)
编辑:
对不起,我的问题不清楚:
- 表1包含22列,表2包含7列
- 查询最多可以有13个筛选器,因此查询必须处理这些筛选器
- 如果可能的话,我宁愿不要超过一个或两个选择
- 一种方法使用聚合。如果不需要按第一个表进行筛选,只需执行以下操作:
select propertyId
from table2
where filter in (1, 2)
group by propertyId
having count(*) = 2; -- "2" = number of things you are looking for
注意:这假设属性/过滤器值在第二个表中是唯一的。否则,您可以使用count(distinct)
编辑:
如果需要按第一个表进行筛选,只需将其添加到:
select t2.propertyId
from table1 t1 join
table2 t2
on t2.propertyId = t1.propertyId
where filter in (1, 2)
group by t2.propertyId
having count(*) = 2; -- "2" = number of things you are looking for
一种方法使用聚合。如果不需要按第一个表进行筛选,只需执行以下操作:
select propertyId
from table2
where filter in (1, 2)
group by propertyId
having count(*) = 2; -- "2" = number of things you are looking for
注意:这假设属性/过滤器值在第二个表中是唯一的。否则,您可以使用count(distinct)
编辑:
如果需要按第一个表进行筛选,只需将其添加到:
select t2.propertyId
from table1 t1 join
table2 t2
on t2.propertyId = t1.propertyId
where filter in (1, 2)
group by t2.propertyId
having count(*) = 2; -- "2" = number of things you are looking for
使用内部联接仅获取连接的键
Select * from table1 inner join table2 on table1.PropertyId = table2.PropertyId where table2.Filter in (1,2)
使用内部联接仅获取连接的键
Select * from table1 inner join table2 on table1.PropertyId = table2.PropertyId where table2.Filter in (1,2)
看看这是否适合您:
select PropertyId
from table1
where PropertyId in
(
select t21.PropertyId
from table2 t21
inner join table2 t22 on t22.PropertyId = t21.PropertyId and t22.Filter = 2
where t21.Filter = 1
)
看看这是否适合您:
select PropertyId
from table1
where PropertyId in
(
select t21.PropertyId
from table2 t21
inner join table2 t22 on t22.PropertyId = t21.PropertyId and t22.Filter = 2
where t21.Filter = 1
)
嗨,戈登,谢谢你的回答,不幸的是,我必须先过滤table@MarcusOhlsson . . . 这很容易处理。嗨,戈登,谢谢你的回答,不幸的是,我必须先过滤table@MarcusOhlsson . . . 这很容易处理。此示例Input的输出是什么?此示例Input的输出是什么?I Sayed,不幸的是,使用内部联接获取表2中具有筛选器1或2的所有行,而不是1和2Hi Sayed,不幸的是,使用内部联接获取表2中具有筛选器1或2的所有行,而不是1和2Hi@Neeray,你是对的,当你只有2个过滤器时,这是有效的,但如果你有12个过滤器会发生什么:),对不起,我没有在我的拳头里澄清这一点question@MarcusOhlsson问题变了,答案也变了。Gordon Linoff的答案可能最适合于有12个过滤器的情况,因为您可以展开in列表并将计数(*)更改为12。您好@Neeray,您的回答是正确的,当您只有2个过滤器时,这会起作用,但如果您有12个过滤器,会发生什么:),对不起,我没有在手里澄清这一点question@MarcusOhlsson问题变了,答案也变了。Gordon Linoff的答案可能最适合有12个过滤器的情况,因为您可以展开in列表并将计数(*)更改为12。