MySql获取两个记录,但不是全部

时间:2015-10-19 11:31:58

标签: mysql

我有这个源数据:

id  p_id    t_id
1   1       1
2   1       2
3   2       1   

我希望看到所有符合序列号p_id 1和2的产品t_id。我不希望看到那些只有t_id 1或2的产品。我也不希望看到每个p_id的重复行。

我尝试使用此查询:

select p_id, t_id from tbl_1 where t_id in (1 , 2)

但它返回:

id  p_id    t_id
1   1       1
2   1       2
3   2       1   

我也试过以下但没有运气:

select p_id, t_id from tbl_1 where t_id = 1 and t_id = 2

感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用以下查询:

SELECT id, p_id, t_id
FROM tbl_1
WHERE p_id IN (
   SELECT p_id
   FROM tbl_1 
   WHERE t_id IN (1 , 2)
   GROUP BY p_id
   HAVING COUNT(DISTINCT t_id) = 2);

这将返回所有tbl_1行,其p_id值与IN运算符的所有值相关,即(1 , 2)。< / p>

如果IN运算符值存储在另一个表中,则可以将查询修改为:

SELECT id, p_id, t_id
FROM tbl_1
WHERE p_id IN (
   SELECT p_id
   FROM tbl_1 
   WHERE t_id IN (SELECT id FROM temp)
   GROUP BY p_id
   HAVING COUNT(DISTINCT t_id) = (SELECT COUNT(*) FROM temp));

答案 1 :(得分:0)

使用group byhaving。如果您只想要p_id

select p_id
from tbl_1
where t_id in (1 , 2)
group by p_id
having count(*) = 2;

获取t_id并不是特别有趣,但您可以使用group_concat()获取它们:

select p_id, group_concat(t_id)
from tbl_1
where t_id in (1 , 2)
group by p_id
having count(*) = 2;