与MySQL交叉查询

时间:2011-09-01 20:36:30

标签: mysql

我试图以这种方式在MySQL中交叉两个查询:

SELECT user_id FROM post GROUP BY thread_id HAVING COUNT(thread_id) = 1
INTERSECT
SELECT user_id FROM post GROUP BY user_id HAVING COUNT(user_id) = 1;

我已经在MySQL中寻找方法,但遗憾的是使用IN和INNER JOIN对我没有用。

我正在使用的测试数据是:

insert into post (post_number, timestamp, user_id, thread_id) values(0,0,1,1000);
insert into post (post_number, timestamp, user_id, thread_id) values(0,0,2,2000);
insert into post (post_number, timestamp, user_id, thread_id) values(0,0,3,2000);
insert into post (post_number, timestamp, user_id, thread_id) values(0,0,4,3000);
insert into post (post_number, timestamp, user_id, thread_id) values(0,0,5,4000);
insert into post (post_number, timestamp, user_id, thread_id) values(0,0,1,4000);

运行我的两个查询的交集应该导致

4

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

在postgres中,我会这样做

SELECT user_id FROM post where thread_id in (
select thread_id from post group by thread_id having count(distinct user_id) = 1)
INTERSECT
SELECT user_id FROM post GROUP BY user_id HAVING COUNT(user_id) = 1;

然而,显然mysql不支持intersect,所以内连接就足够了:

SELECT post.user_id FROM post 
join (SELECT user_id FROM post GROUP BY user_id HAVING COUNT(user_id) = 1) x on x.user_id = post.user_id
where 
post.thread_id in (
select thread_id from post group by thread_id having count(distinct user_id) = 1)

这两个都返回4

答案 1 :(得分:1)

那么,您想要一个已发布一个孤立线程的用户列表吗?也许一个子选择效果最好。

SELECT user_id
  FROM (
    SELECT user_id
      FROM post
      GROUP BY thread_id
      HAVING COUNT(thread_id) = 1
  ) AS orphan
  GROUP BY user_id
  HAVING COUNT(user_id) = 1
编辑:是的,上面的错误;我没想得够。这是另一回事,但不要抱有希望:

SELECT user_id
  FROM (
    SELECT user_id
      FROM post
      GROUP BY thread_id
      HAVING COUNT(thread_id) = 1
  ) AS orphan_post
  INNER JOIN (
    SELECT user_id
      FROM post
      GROUP BY user_id
      HAVING COUNT(user_id) = 1
  ) AS orphan_user
  ON user_id