【问题标题】:How do I properly combine these SELECTS (MySQL)?如何正确组合这些 SELECTS (MySQL)?
【发布时间】:2021-08-26 18:29:08
【问题描述】:

我想使用此 SELECT 获取我所有的帖子数据以显示在我的网页上。我的表格帖子包含大部分帖子(+回复)数据和一个表格社交,可以跟踪谁查看和喜欢它(每个喜欢都是一个新行)。 通常我可以获得用户名、发布时间、内容......但我很难获得帖子获得的查看次数、喜欢的次数以及同一 SELECT 中的回复次数。我的基本 SELECT 如下所示:

SELECT posts.username, posts.time, cat.cat_name, 
posts.title, posts.content, posts.reply, 
posts.user_file, posts.audio, social.id, 
social.views, social.likes 
FROM posts 
LEFT JOIN user on posts.user_id = user.id 
LEFT JOIN cat ON posts.cat_id = cat.id
LEFT JOIN social ON posts.id = social.post_id

如果我想获得每个帖子的 cmets 数量,我会使用 (如果回复中的值为 0,则它是一个帖子,如果它是一个回复,它包含它所指的帖子 ID):

SELECT COUNT(*) AS `comments` FROM posts GROUP BY reply
/* this returns an error: SQL Error (1242): Subquery returns more than 1 row */

我会得到这样的喜欢和观看次数:

SELECT MAX(social.views) AS views FROM social GROUP BY post_id

SELECT social.likes FROM social WHERE social.id = (SELECT MAX(social.id) FROM social GROUP BY post_id

但如果我在前面的 SELECT 中一起使用它,它只会用相同的数字填充每一行。示例:

... posts.audio, social.id, (SELECT MAX(social.views) AS views FROM social GROUP BY post_id) FROM posts ...

这只会填充每一行,即使它不应该有 25 的视图(1 个特定行的正确值,但其他所有内容都是错误的)。

像这样制作更大的 SELECT 的正确方法是什么?

不确定是否重要,但我在 NodeJS 中将它与 MySQL 模块一起使用。

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。您的表格中的内容并不明显。

标签: mysql sql


【解决方案1】:

试试这个方法

SELECT posts.username, posts.time, cat.cat_name, 
posts.title, posts.content, posts.reply, 
posts.user_file, posts.audio, 
COUNT(social.views), COUNT(social.likes)
FROM posts 
LEFT JOIN user on posts.user_id = user.id 
LEFT JOIN cat ON posts.cat_id = cat.id
LEFT JOIN social ON posts.id = social.post_id
GROUP BY
posts.username, posts.time, cat.cat_name, 
posts.title, posts.content, posts.reply, 
posts.user_file, posts.audio

【讨论】:

  • 谢谢。你的帖子很有帮助。
【解决方案2】:

这是我最接近在一个查询中选择所有内容的方法,但我仍然无法计算 cmets 的数量:

SELECT posts.username, posts.time, cat.cat_name, 
posts.title, posts.content, posts.reply,
posts.user_file, posts.audio,
social.views, social.likes
FROM posts
LEFT JOIN user on posts.user_id = user.id 
LEFT JOIN cat ON posts.cat_id = cat.id
LEFT JOIN social ON posts.id = social.post_id
WHERE social.likes IN (SELECT social.likes FROM social 
WHERE social.id IN (SELECT MAX(social.id) 
FROM social GROUP BY post_id))
GROUP BY social.post_id
HAVING posts.reply = 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2014-07-18
    • 2011-02-24
    相关资源
    最近更新 更多