Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL从两个表中选择_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

SQL从两个表中选择

SQL从两个表中选择,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我的第一张表如下(不重要): 待决项目 ItemId,ItemName 1 ,'test' 2 ,'test2' 3 , 'test3' 第二个表是(重要表),这个表告诉我们ItemId有什么规格?例如,ItemId1具有规范5、6和7 tbl_规范 ItemId , SpecId 1 ,5 1 ,6 1 ,7 2 ,5 2 ,8 3 ,5 3 ,7 如何选择SpecId为5和7的项目 结果必须是:

我的第一张表如下(不重要):

待决项目

ItemId,ItemName
1     ,'test'
2     ,'test2'
3     , 'test3'
第二个表是(重要表),这个表告诉我们
ItemId
有什么规格?例如,
ItemId
1具有规范5、6和7

tbl_规范

ItemId , SpecId
1      ,5
1      ,6
1      ,7
2      ,5
2      ,8
3      ,5
3      ,7
如何选择SpecId为5和7的项目

结果必须是:

ItemId
1
3
ItemId
1
3
(…)中的SQL默认使用OR,但我希望使用And函数


我的DBMS是SQL Server 2008

这将提供您所要求的输出,但我不能100%确定这是否是您所要求的

select distinct itemID
from tbl_Spec
where SpecId in (5,7)

执行以下sql查询


从tblłU规范中选择ItemId,其中SpecId在(5,7)

我肯定会有更优雅的方式,但这会给你你想要的(编辑:根据MichaełPowaga的建议修复)

p、 阿里,如果你需要一个更容易扩展的解决方案,你看到米凯尔·埃里克森的答案了吗

select itemid from
(
    select itemid from tbl_spec where specid = 5
) subset1 inner join
(
    select itemid from tbl_spec where itemid = 7
) subset2 on subset1.itemid = subset2.itemid
结果:


我希望它对你有用。

为了得到结果,应该使用什么规则?我看不到与您的数据的直接连接。我希望项目Id同时具有规范5和7。项目Id 2只有5,但项目Id 1和3的值中都有5和7。我希望它同时有5和7,而不仅仅是其中一个,我更改了问题示例,并添加了项目Id 2,5。您想要什么同时有5和7?上面的查询将为您提供请求的结果集。您的查询还返回ItemId 2,我不需要它。很抱歉,是的,误解了问题。否,因为将选择Item 2,我不需要它。在(…)中执行OR函数,但我想要and函数。谢谢,但是您有可扩展的解决方案吗?很好,但我会将
having
更改为
having COUNT(distinct SpecId)>1
以防
SpecId=5
对于相同的
ItemId
存在两次。@AliRezza将
where
条件更改为
在(…)
和在
中,让
部分放置所需的2个项目数量可能是
=2
,3个
=3
等等。感谢Paolo,您的解决方案更好,我将其更改为(5,7)。这是更复杂查询的一部分,使用这种方式对我来说比其他方式更好。谢谢,但是你有一个可扩展的解决方案吗?谢谢亲爱的Mikael提供的解决方案,你的解决方案很好,但是因为这个查询是更复杂查询的一部分,我接受了另一个答案。
select * from (select Count(ItemID)Counted from tbl_Spec where Itemid in (select Itemid  from tbl_Item )and SpecId in(5,7) group by ItemID) a where Counted>=2
ItemId
1
3
select distinct ItemId from tbl_Item, tbl_Spec 
where tbl_Item.ItemId=tbl_Spec.ItemId 
and tbl_SPec.SpecId not in (select SpecId from tbl_Spec where SpecId not in (5,7))
select * from (select Count(ItemID)Counted from tbl_Spec where Itemid in (select Itemid  from tbl_Item )and SpecId in(5,7) group by ItemID) a where Counted>=2