开发者

problem with join SQL Server 2000

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜