gpt4 book ai didi

mysql - SQL查询多重连接

转载 作者:行者123 更新时间:2023-11-29 14:30:00 26 4
gpt4 key购买 nike

已修订。我的 SQL 有限,非常感谢您的帮助。在一次命中中,我想通过 ID ($ga_id) 查询两个表,每个表都与另一个表有内部联接(表具有完全相同的列,并且父表彼此没有关系)。

我可以成功查询net_5_postmeta表,如下

SELECT p.*
FROM net_5_postmeta AS pm
INNER JOIN net_5_posts AS p ON pm.meta_value=p.ID
WHERE pm.post_id = $ga_id
AND pm.meta_key = '_thumbnail_id'
ORDER BY p.post_date DESC
LIMIT 4

但我想查询 net_5_postmeta 表和 net_7_postmeta 表(它们具有相同的列),我认为它需要类似于...

SELECT p.*
FROM net_5_postmeta, net_7_postmeta AS pm
INNER JOIN net_5_posts AS p ON pm.meta_value=p.ID
INNER JOIN net_7_posts AS p ON pm.meta_value=p.ID
WHERE pm.post_id = $ga_id
AND pm.meta_key = '_thumbnail_id'
ORDER BY p.post_date DESC
LIMIT 4

最佳答案

正如您所说,父表没有关系,我只能假设您希望将 57 表视为相同的表。您应该使用 union all 将它们的数据组合在一起,然后执行 ORDER BY/LIMIT。

SELECT *
FROM
(
SELECT p.*
FROM net_5_postmeta AS pm
INNER JOIN net_5_posts AS p ON pm.meta_value=p.ID
WHERE pm.post_id = $ga_id
AND pm.meta_key = '_thumbnail_id'

UNION ALL

SELECT p.*
FROM net_7_postmeta AS pm
INNER JOIN net_7_posts AS p ON pm.meta_value=p.ID
WHERE pm.post_id = $ga_id
AND pm.meta_key = '_thumbnail_id'
) united
ORDER BY united.post_date DESC
LIMIT 4

关于mysql - SQL查询多重连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10176484/

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