简体   繁体   English

SQL从两个表中选择

[英]SQL select from two tables

My first table is as below (not important): 我的第一张桌子如下(不重要):

tbl_Item tbl_Item

ItemId,ItemName
1     ,'test'
2     ,'test2'
3     , 'test3'

and second table is (Important table),this table tell us that ItemId has what specifications? 第二个表是(重要表),该表告诉我们ItemId有什么规格? For example ItemId 1 has specs 5 and 6 and 7 例如, ItemId 1具有规格5、6和7

tbl_Spec tbl_Spec

ItemId , SpecId
1      ,5
1      ,6
1      ,7
2      ,5
2      ,8
3      ,5
3      ,7

How can I select Items that have both SpecId 5 and 7 如何选择同时具有SpecId 5和7的项目

the result must be : 结果必须是:

ItemId
1
3

SQL In (...) do the OR as default, but I want something with And Function. SQL In(...)作为默认值执行OR,但我想要使用And Function。

My DBMS is SQL Server 2008 我的DBMS是SQL Server 2008

I'm sure there must be more elegant ways, but this should give you what you want (EDIT: fixed as per Michaeł Powaga's suggestion). 我确定必须有更优雅的方法,但这应该可以为您提供所需的信息(编辑:根据MichaełPowaga的建议进行了修正)。

SELECT ItemId
FROM tbl_Spec
WHERE SpecId=5 OR SpecId=7
GROUP BY ItemId
HAVING COUNT(DISTINCT SpecId)=2

ps Ali , if you need a more easily expandable solution, have you seen Mikael Eriksson's answer? ps Ali,如果您需要一个更容易扩展的解决方案,您是否看到了Mikael Eriksson的答案?

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
declare @T table
(
  ItemId int,
  SpecId int
)

insert into @T values
(1      ,5),
(1      ,6),
(1      ,7),
(2      ,5),
(2      ,5),
(2      ,8),
(3      ,5),
(3      ,7),
(4      ,5),
(4      ,5)

;with C(SpecId) as
(
  select 5 union all
  select 7
)
select T.ItemId
from @T as T
  inner join C
    on T.SpecId = C.SpecId
group by T.ItemId
having count(distinct T.SpecId) = (select count(*) from C)

Result: 结果:

ItemId
1
3

This will give the desired output you requested, but I'm not 100% sure if this is what you are asking for. 这将提供您所需的期望输出,但是我不确定100%是否是您所要的。

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

Do the following sql query 执行以下SQL查询

select ItemId from tbl_Spec where SpecId in (5,7) 从tbl_Spec中选择ItemId,其中(5,7)中的SpecId

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))

I hope it works for you. 我希望这个对你有用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM