gpt4 book ai didi

mysql - 组合两个不同的查询

转载 作者:行者123 更新时间:2023-11-29 13:10:06 25 4
gpt4 key购买 nike

我有两个查询选择相似的列,但具有不同的 WHEREJOIN 子句。我需要将这两个查询与 UNION 结合起来,以便总共显示 26 个结果(组合),按日期排序。我不知道如何使用以下两个查询来做到这一点。

第一个查询:

SELECT p.post_id,
p.reply_to,
p.parent_id,
p.post_path,
p.user_id,
p.content,
p.datetime,
p.total_likes,
p.total_replies,
p.total_reposts,
u.username,
u.display_name,
l.like_id,
l.user_id
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON (l.post_id = p.post_id AND l.user_id = ?)
WHERE p.user_id IN (SELECT following_id FROM follows WHERE user_id = ?)
AND p.removed != 1
ORDER BY p.datetime DESC LIMIT 26

第二个查询:

SELECT p.post_id,
p.reply_to,
p.parent_id,
p.post_path,
p.user_id,
p.content,
p.datetime,
p.total_likes,
p.total_replies,
p.total_reposts,
u.username,
u.display_name,
l.like_id,
l.user_id
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON l.post_id = p.post_id
WHERE l.user_id IN (SELECT user_id FROM likes WHERE user_id IN (SELECT following_id FROM follows WHERE user_id = ? AND following_id != ?))
AND l.user_id != p.user_id AND p.removed != 1
ORDER BY p.datetime DESC LIMIT 26

我该怎么做?

最佳答案

您应该能够在两个 select 语句之间放置 UNION 或 UNION ALL。另外,请确保删除第一个 ORDER BY,否则会引发错误。应运行以下语句。

SELECT p.post_id,
p.reply_to,
p.parent_id,
p.post_path,
p.user_id,
p.content,
p.datetime,
p.total_likes,
p.total_replies,
p.total_reposts,
u.username,
u.display_name,
l.like_id,
l.user_id
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON (l.post_id = p.post_id AND l.user_id = ?)
WHERE p.user_id IN (SELECT following_id FROM follows WHERE user_id = ?)
AND p.removed != 1
UNION
SELECT p.post_id,
p.reply_to,
p.parent_id,
p.post_path,
p.user_id,
p.content,
p.datetime,
p.total_likes,
p.total_replies,
p.total_reposts,
u.username,
u.display_name,
l.like_id,
l.user_id
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON l.post_id = p.post_id
WHERE l.user_id IN (SELECT user_id FROM likes WHERE user_id IN (SELECT following_id FROM follows WHERE user_id = ? AND following_id != ?))
AND l.user_id != p.user_id AND p.removed != 1
ORDER BY p.datetime DESC LIMIT 26

关于mysql - 组合两个不同的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22209069/

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