如何在IN查询中完全完成选择行?

时间:2017-03-28 08:40:26

标签: mysql

我们有一个包含两列的表格 - art_idcat_id。 我们需要选择行WHERE cat_id = 12,13,15

我试着做点什么:

SELECT art_id 
FROM table 
WHERE cat_id IN (12,13,15) 
GROUP BY art_id 
HAVING COUNT(cat_id) > 2

但是这个选择也选择了art_id = 4 AND 9。

table example

预期输出:

art_id = 1 and 7

3 个答案:

答案 0 :(得分:1)

假设你事先没有知道art_ids,也许是这个?

SELECT art_id, GROUP_CONCAT(cat_id SEPARATOR ',') as concatenated
FROM table
GROUP BY art_id
HAVING concatenated = '12,13,15'

如果每组中的序列可以不同。例如。 13,12,15然后你也需要对组合进行排序。

SELECT art_id, 
  GROUP_CONCAT(DISTINCT cat_id ORDER BY cat_id ASC SEPARATOR ',') AS concatenated
FROM table
GROUP BY art_id
HAVING concatenated = '12,13,15'

答案 1 :(得分:0)

我希望这对你有用

SELECT art_id 
FROM table 
WHERE cat_id IN (12,13,15) 
AND (art_id = 4 OR art_id = 7) 
GROUP BY art_id 
HAVING COUNT(cat_id) > 2

答案 2 :(得分:0)

你可以试试这个,但只有当你没有art_id,cat_id重复时它才有效:例如:如果你将样本数据加INSERT INTO T1 VALUES (9,15)两次,它就不起作用

 SELECT DISTINCT T1.art_id
 FROM T1
 INNER JOIN (SELECT art_id, COUNT(*) AS RC
             FROM T1
             WHERE CAT_ID IN (12,13,15)
             GROUP BY art_id) X ON T1.art_id = X.art_id
 WHERE X.RC>2

输出:

art_id
-----------
1
7