MSSQL选择“垂直” - 其中

时间:2012-02-14 12:37:33

标签: sql-server select relational-division

我真的不知道如何解释除了“垂直在哪里”。

想象一下下表:

TAGID|PRODUCTID|SHOP_ID
59   |3418-7   |38
61   |3418-7   |38
60   |4227-4   |38
61   |4227-4   |38

现在我想返回与标签ID有关的所有产品ID:59,61。换句话说,两个标记ID的行存在的产品ID的值。

所以我想返回3418-7,但不是4227-4

如何在SQL语句中尽可能简单地编写它?

这是我到目前为止的工作声明,但我觉得这可以用更聪明的方式完成:

SELECT 
  productid 
FROM shop_tag_relations 
WHERE 
  productid IN (select productid from shop_tag_relations WHERE tagid=59) 
AND 
  productid IN (select productid from shop_tag_relations WHERE tagid=61)
GROUP BY productid,shop_id

3 个答案:

答案 0 :(得分:8)

SELECT PRODUCTID
FROM T
WHERE TAGID IN (59,61)
GROUP BY PRODUCTID
HAVING COUNT(DISTINCT TAGID) = 2

或者

SELECT PRODUCTID
FROM T
WHERE TAGID = 59
INTERSECT
SELECT PRODUCTID
FROM T
WHERE TAGID = 61

答案 1 :(得分:2)

SELECT DISTINCT 
a.PRODUCTID 
FROM mytable AS a
INNER JOIN mytable AS b ON a.PRODUCTID=b.PRODUCTID
WHERE a.TAGID=59
AND b.TAGID=61
;

答案 2 :(得分:1)

SELECT ProductId
FROM shop_tag_relations 
WHERE TAGID IN (59,61)
GROUP BY ProductId
HAVING COUNT(DISTINCT TagId) = 2