大家好,我有一张包含两列trial_id
,category_id
我正在附加图像以使其更清晰。
当我想要trial_id
category_id
的记录时,我可以运行
SELECT * FROM `trial_category` WHERE category_id IN ( 259, 260 )
您可以将trial_id
与这两个category_id
我的问题是,现在我希望与这两个trial_id
完全匹配的category_id
我该怎么办?
意味着如果你只注意trial_id
73同时拥有259和260 category_id
那么我的结果应该只有73。
感谢
答案 0 :(得分:1)
SELECT trial_id, count(trial_id) AS ccnt
FROM trial_category
WHERE category_id IN ( 259,260)
GROUP BY trial_id
HAVING ccnt = 2
答案 1 :(得分:1)
使用group by子句:
SELECT trail_id FROM `trial_category`
WHERE category_id IN ( 259, 260 )
GROUP BY trial_id
HAVING count(trial_id) = 2
答案 2 :(得分:1)
这是“set-within-sets”子查询的示例。以下是使用group by
having
子句的解决方案:
SELECT trial_id
FROM trial_category
group by trial_id
having sum(case when category_id = 259 then 1 else 0 end) > 0 and
sum(case when category_id = 260 then 1 else 0 end) > 0;
当其中一行具有特定类别时,满足having
子句中的每个条件。您可以看到这很容易概括为更多类别。甚至是案件259但不是260和261。
如果您希望完全这两个类别,您可以通过添加此子句来过滤没有任何其他类别的行:
sum(case when category_id not in (259, 260) then 1 else 0 end) = 0;
IN(259,260)
答案 3 :(得分:0)
您需要GROUP BY
使用trial_id
SELECT q.* FROM (
SELECT *,COUNT(trial_id) as tcount FROM trial_category
WHERE category_id IN ( 259, 260 ) GRUOP BY trial_id ) q
WHERE q.tcount >1
OR
SELECT *,COUNT(trial_id) as tcount FROM trial_category
WHERE category_id IN ( 259, 260 ) GRUOP BY trial_id HAVING tcount >1
答案 4 :(得分:0)
试试这个
SELECT DISTINCT trail_id FROM `trail_category` WHERE category_id IN ( 259, 260 );