gpt4 book ai didi

mysql - 如何将四个查询合并为一个查询?

转载 作者:行者123 更新时间:2023-11-29 08:31:51 28 4
gpt4 key购买 nike

我的表格结构:

posts (id, name, user_id, about, time)    
comments (id, post_id, user_id, text, time)
users_votes (id, user, post_id, time)
users_favs ( id, user_id, post_id, time)

如何组合这四个查询(不使用 UNION):

SELECT `id`, `name`, `user_id`, `time` FROM `posts` WHERE `user_id` = 1
SELECT `post_id`, `user_id`, `text`, `time` FROM `comments` WHERE `user_id` = 1
SELECT `user`, `post_id`, `time` FROM `users_votes` WHERE `user` = 1
SELECT `user_id`, `post_id`, `time` FROM `users_favs` WHERE `user_id` = 1

我应该使用JOIN吗?

这个 SQL 查询是什么?

最佳答案

您不想将它们连接在一起。

您用来检索此内容的 JOIN 类型最终会对其找到的所有行进行叉积。这意味着,如果您有 4 个帖子、2 个评论、3 个投票和 6 个收藏,那么在执行单独查询时,您的结果中将获得 4*2*3*6 行,而不是 4+2+3+6。

您想要加入的唯一时间是当两件事本质上相关时。也就是说,您想要检索与收藏夹、投票或评论相关的帖子。

根据您的示例,这些事情没有这样的共性。

关于mysql - 如何将四个查询合并为一个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16349684/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com