我有3张桌子 1.用户
name surname id birthdate
Lowell Bishop 1 1981-05-19
Rodney Miller 2 1968-01-15
Binyamin Boone 3 1991-12-21
2。友谊
userid1 userid2 timestamp
1 2 2018-12-03 20:11:03
1 3 2018-02-02 05:36:32
2 3 2018-01-16 02:50:08
3个赞
userid postid timestamp
1 4 2018-05-15 21:38:52
2 195 2018-11-17 09:28:43
3 252 2018-10-26 07:08:12
我有2个查询
/ 查询可获取在2018年3月拥有5个以上朋友的用户 /
SELECT count(u1.id) as friends_count,
u1.id, u1.name,u1.surname FROM users u1
INNER JOIN friendships f ON f.userid1 = u1.id
INNER JOIN users u2 ON u2.id = f.userid2
where f.timestamp >= '2025-03-01' and f.timestamp <= '2025-03-31'
group by u1.id
having count(f.userid1) >= 5
order by u1.id;
/ 查询可让用户在2018年3月获得5个以上的点赞 /
SELECT count(u1.id) as likes_count,u1.id, u1.name,u1.surname FROM users u1
INNER JOIN likes l ON u1.id = l.userid
where l.timestamp >= '2025-03-01' and l.timestamp <= '2025-03-31'
group by u1.id
having count(u1.id) >= 5
order by u1.id;
如何将此2个查询相交为1个?我使用MySQL,所以相交给我一个错误。我正在尝试将此结果放入1个表中,如下所示:
friends_count likes_count id name surname
5 4 78 Joselyn Lynn
答案 0 :(得分:1)
您可以在下面尝试-使用子查询
select * from
(
SELECT count(u1.id) as friends_count,
u1.id, u1.name,u1.surname FROM users u1
INNER JOIN friendships f ON f.userid1 = u1.id
INNER JOIN users u2 ON u2.id = f.userid2
where f.timestamp >= '2025-03-01' and f.timestamp <= '2025-03-31'
group by u1.id
having count(f.userid1) >= 5
)A inner join
(
SELECT count(u1.id) as likes_count,u1.id, u1.name,u1.surname FROM users u1
INNER JOIN likes l ON u1.id = l.userid
where l.timestamp >= '2025-03-01' and l.timestamp <= '2025-03-31'
group by u1.id
having count(u1.id) >= 5
)B on A.ud=B.id