I am trying to intersect two querys in MySQL in this fashion:
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;
I've looked for ways to do it in MySQL, but unfortunately using IN and INNER JOIN hasn't worked for me.
The test data I'm working with is:
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 pos开发者_如何学Ct (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);
Running an intersection of my two queries should result in
4
Any help is appreciated, thanks.
In postgres I'd do it like this
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;
However, apparently mysql doesn't support intersect, so an inner join will suffice:
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)
Those both return 4
So, you want a list of users who have posted one orphan thread? Maybe a subselect works best.
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
EDIT: Yeah, the above was wrong; I didn't think about it enough. Here's another go, but don't get your hopes up:
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
精彩评论