代码之家  ›  专栏  ›  技术社区  ›  Martin AJ

我可以使用join而不是返回一行的子查询吗?

  •  0
  • Martin AJ  · 技术社区  · 6 年前

    我的问题是:

    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 (而不是子查询) . 有可能吗?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Tim Biegeleisen    6 年前

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

    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 . 因此,我们可以连接到一个子查询,该子查询查找 身份证件 每个的价值 后亲 小组。那么,我们需要再次加入 wp_posts 引进 guid 最大值 身份证件 划船。

        2
  •  1
  •   Noor A Shuvo    6 年前

    你可以用

    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
    
        3
  •  0
  •   RoverRoll    6 年前

    试试这个

    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