如何在其他基础上从表中选择数据

时间:2018-05-22 12:23:50

标签: mysql

我有2张桌子T1和T2。这里T1包含博客,T2包含喜欢发帖的用户列表。

T1数据库架构post_id,发布

T2数据库架构post_id,user_id

我想只选择至少有10个用户喜欢的帖子。

6 个答案:

答案 0 :(得分:1)

SELECT T1.post_id, T1.post, COUNT(T2.user_id]) as Total
FROM T1 JOIN T2 ON T1.post_id = T2.post_id 
GROUP BY T1.post_id, T1.post 
HAVING Total >= 10

答案 1 :(得分:0)

您可以对选择进行分组,然后使用having

SELECT posts.*, COUNT(likes.id) as likesCount
FROM posts, likes
GROUP BY posts.id HAVING (likesCount >= 10)

答案 2 :(得分:0)

在表格 T2 中,发生超过10的post_id是您想要的帖子,因此您可以选择在表格中至少10行发布post_id的帖子 T2

答案 3 :(得分:0)

您可以使用子选择吗?

SELECT post_id,COUNT(post_id) AS count,
(SELECT post FROM T1 where post_id=T2.post_id) AS post
GROUP BY post_id
HAVING count >= 10

答案 4 :(得分:0)

为了获得最佳性能并避免使用“笛卡尔产品”,请使用join,如下所示:

SELECT p.post_id, COUNT(l.user_id) AS TotalLikesCount
FROM posts AS p
JOIN likes AS l ON p.post_id = l.post_id
GROUP BY p.post_id
HAVING TotalLikesCount >= 10

答案 5 :(得分:0)

您可以使用加入选择帖子。

SELECT p.post_id, p.post, count(pl.user_id) as likes 
FROM `post` as p
join post_likes as pl on p.post_id = pl.post_id

where 1 group by pl.post_id
having likes >= 10;