我需要帮助才能在MySQL中找到此查询的解决方案?

时间:2016-11-27 07:55:52

标签: mysql laravel

我有MySQL表如下:

id  p_id   c_id

1   11      1

2   11      2

3   11      3

4   12      1

5   12      3

6   13      1

7   13      2

我需要一个查询,当c_id为1和2时,它应该返回p_id的11和13。

我尝试了以下查询:

SELECT DISTINCT p_id FROM `Table Name` where c_id in (1,2)

返回:11, 12, 13

但我只需要它返回:11 , 13

4 个答案:

答案 0 :(得分:2)

您可以将查询编写为:

SELECT DISTINCT a.p_id 
FROM table_name AS a
JOIN table_name AS b ON a.p_id=b.p_id
WHERE a.c_id ='1' AND b.c_id ='2';

这是桌面上的自我加入

答案 1 :(得分:2)

SELECT DISTINCT a.p_id 
FROM table_name AS a
JOIN table_name AS b ON a.p_id=b.p_id
WHERE a.c_id ='1' AND b.c_id ='2';

它对我有用

答案 2 :(得分:0)

您的查询正在检查与c_is 1 相关的p_ids 2.但您想要的是1 2.您可以这样写:

SELECT DISTINCT t1.p_id 
FROM table_name as t1
JOIN table_name as t2
    ON t1.id = t2.id
WHERE t1.c_id = 1 AND t2.c_id = 2;

答案 3 :(得分:0)

SELECT x.id
  FROM my_table x
 WHERE other_column IN('a','b')
 GROUP 
    BY x.id
HAVING COUNT(*) = 2;