0

大家好,我有一个有两列的表trial_idcategory_id

我正在附加图像,以便它变得更清晰。

当我想要其中的记录时trial_idcategory_id我可以运行如下查询

 SELECT * FROM `trial_category` WHERE category_id IN ( 259, 260 )

您可以将其trial_id与这两者联系起来category_id

我的问题是,现在我想要trial_id与这两个完全匹配的category_id我该怎么办?

意味着如果你注意到只有trial_id73 有 259 和 260,category_id那么我的结果应该只有 73。

谢谢在此处输入图像描述

4

5 回答 5

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
于 2013-07-03T10:49:48.213 回答
1

使用 group by 子句:

SELECT trail_id FROM `trial_category` 
WHERE category_id IN ( 259, 260 ) 
GROUP BY trial_id
HAVING count(trial_id) = 2
于 2013-07-03T10:50:06.060 回答
1

这是“set-within-sets”子查询的一个示例。这是使用group bywithhaving子句的解决方案:

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;

在 ( 259, 260 )

于 2013-07-03T10:52:50.943 回答
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

或者

SELECT *,COUNT(trial_id) as tcount FROM trial_category 
WHERE category_id IN ( 259, 260 ) GRUOP BY trial_id  HAVING tcount >1
于 2013-07-03T10:50:03.397 回答
0

尝试这个

  SELECT DISTINCT trail_id FROM `trail_category` WHERE category_id IN ( 259, 260 );
于 2013-07-03T10:53:06.990 回答