我可以用join代替返回1行的子查询吗?

apeeds0o  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(285)

我的问题是:

SELECT p1.*,
       (select guid
        from wp_posts p2
        where p2.post_parent = p1.id
        ORDER by p2.id DESC
        LIMIT 1) as post_image
from wp_posts p1
where p1.post_status = 'publish' and
      p1.post_type = 'post'
order by p1.id DESC limit 4

我想进行相同的查询,但使用 join (而不是子查询)。有可能吗?

jqjz2hbq

jqjz2hbq1#

试试这个

SELECT p1.*       
from wp_posts p1
left outer join(select guid
        from wp_posts 
        where p2.post_parent = p1.id
        ORDER by p2.id DESC
        LIMIT 1) as post_image
where p1.post_status = 'publish' and
      p1.post_type = 'post'
order by p1.id DESC limit 4
py49o6xq

py49o6xq2#

你可以用

SELECT p1.*, p2.guid FROM 
wp_posts as p1 
JOIN wp_post AS p2 ON  p2.post_parent = p1.id 
AND p1.post_status = 'publish' AND p1.post_type = 'post'
ORDER by p1.id DESC limit 1
ha5z0ras

ha5z0ras3#

我们可以尝试使用一系列额外的连接重写:

SELECT
    p1.*,
    COALESCE(t2.guid, 'NA') AS post_image
FROM wp_posts p1
LEFT JOIN
(
    SELECT post_parent, MAX(id) AS max_id
    FROM wp_posts
    GROUP BY post_parent
) t1
    ON p1.id = t2.post_parent
LEFT JOIN wp_posts t2
    ON t1.max_id = t2.id
WHERE p1.post_status = 'publish' AND p1.post_type = 'post'
ORDER BY p1.id DESC
LIMIT 4;

根据观察,上述重构背后的逻辑是,您当前的子查询正在为 post_parent ,最大值为 id . 因此,我们可以连接到一个子查询,该子查询查找最大值 id 每个的值 post_parent 组。那么,我们需要再次加入 wp_posts 引进 guid 最大值 id 行。

相关问题