簡體   English   中英

SQL從兩個表中選擇

[英]SQL select from two tables

我的第一張桌子如下(不重要):

tbl_Item

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

第二個表是(重要表),該表告訴我們ItemId有什么規格? 例如, ItemId 1具有規格5、6和7

tbl_Spec

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

如何選擇同時具有SpecId 5和7的項目

結果必須是:

ItemId
1
3

SQL In(...)作為默認值執行OR,但我想要使用And Function。

我的DBMS是SQL Server 2008

我確定必須有更優雅的方法,但這應該可以為您提供所需的信息(編輯:根據MichaełPowaga的建議進行了修正)。

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

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)

結果:

ItemId
1
3

這將提供您所需的期望輸出,但是我不確定100%是否是您所要的。

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

執行以下SQL查詢

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

我希望這個對你有用。

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