开发者

problem with join SQL Server 2000

开发者 https://www.devze.com 2022-12-10 06:21 出处:网络
I have 3 tables - Items, Props, Items_To_Props i need to return all items that match all properties that i send

I have 3 tables - Items, Props, Items_To_Props

i need to return all items that match all properties that i send example

items
1 
2
3
4

props开发者_开发问答
T1
T2
T3

items_to_props
1 T1
1 T2
1 T3
2 T1
3 T1

when i send T1,T2 i need to get only item 1


SELECT T.itemId
  FROM (SELECT itemId, count(distinct prop) propCount
          FROM items_to_props
         WHERE prop in ('T1', 'T2')
      GROUP BY itemId) T
WHERE T.propCount = 2

If you don't know how many props you have, you can create a temp table #P(prop), populate it with your props and run the folowing query (will do the same thing):

SELECT T.itemId
  FROM (SELECT i.itemId, count(distinct p.prop) propCount
          FROM items_to_props i
          JOIN #P p on i.prop = p.prop
      GROUP BY i.itemId) T
WHERE T.propCount = (SELECT COUNT(DISTINCT prop) FROM #P)


It is correct that you only get one row for T2, you should get 3 for T1

0

精彩评论

暂无评论...
验证码 换一张
取 消