查询以选择具有两个精确记录的对象

时间:2016-08-18 13:23:02

标签: mysql sql

我在MySQL中有以下表格:

some_table

user_id | obj_id
-----------------
5       | 1
6       | 1
7       | 2
8       | 2

现在我需要一个查询,如果此obj_id同时具有user_id = 5user_id = 6(在上面的示例中为obj_id=1),则会向我提供obj_id。

MySQL是否可以这样?

2 个答案:

答案 0 :(得分:5)

一种方法使用group byhaving

select obj_id
from some_table t
where user_id in (5, 6)
group by obj_id
having count(distinct user_id) = 2;

答案 1 :(得分:2)

由于@GordonLinoff已经提供了更好的解决方案。

但这是使用INTERSECT获得预期结果的可能方法之一:

SELECT DISTINCT obj_id FROM @TEST WHERE user_id = 5
INTERSECT
SELECT DISTINCT obj_id FROM @TEST WHERE user_id = 6

示例执行:

CREATE TABLE some_table (`user_id` INT, obj_id INT);

INSERT INTO some_table (`user_id`, obj_id) VALUES 
(5, 1),
(6, 1),
(7, 2),
(8, 2),
(5, 3),
(6, 4);

SELECT DISTINCT obj_id FROM some_table WHERE `user_id` = 5
INTERSECT
SELECT DISTINCT obj_id FROM some_table WHERE `user_id` = 6

结果将是1