代码之家  ›  专栏  ›  技术社区  ›  unrelativity

左连接上的MySQL限制

  •  2
  • unrelativity  · 技术社区  · 15 年前

    我的问题是:

       SELECT issues.*, 
              comments.author AS commentauthor, 
              comments.when_posted AS commentposted
         FROM issues
    LEFT JOIN (SELECT * 
                 FROM comments 
             ORDER BY when_posted DESC 
                LIMIT 1) AS comments ON issues.id=comments.issue
    ORDER BY IFNULL(commentposted, issues.when_opened) DESC
    

    如果我从那里删除“限制1”部分,我会得到一个问题中每个评论的一行,而这不是我想要的。我想要的只是每个问题的最新评论。

    3 回复  |  直到 15 年前
        1
  •  2
  •   manji    15 年前
       SELECT issues.*, 
              comments.author AS commentauthor, 
              comments.when_posted AS commentposted
         FROM issues
    LEFT JOIN ( SELECT c1.issue, c1.author, c1.when_posted
                  FROM comments c1
               JOIN
               (SELECT c2.issue, max(c2.when_posted) AS max_when_posted           
                  FROM comments c2
              GROUP BY issue) c3
                on c1.issue = c3.issue and c1.when_posted = c3.max_when_posted
              ) AS comments ON issues.id=comments.issue
     ORDER BY COALESCE(commentposted, issues.when_opened) DESC
    
        2
  •  3
  •   OMG Ponies    15 年前

    尝试:

       SELECT i.*,
              c.author AS commentauthor,
              c.when_posted AS commentposted
         FROM ISSUES i
    LEFT JOIN COMMENTS c ON c.issue = i.id
         JOIN (SELECT c.issue,
                      MAX(c.when_posted) 'max_when_posted'
                 FROM COMMENTS c
             GROUP BY c.issue) mwp ON mwp.issue = c.issue
                                  AND mwp.max_when_posted = c.when_posted
     ORDER BY COALESCE(c.when_posted, i.when_opened) DESC
    
        3
  •  0
  •   Joel Coehoorn    15 年前

    编辑

    由于MySql毕竟没有CTE,请尝试以下方法:

    SELECT i.*
        c.author AS CommentAuthor,
        c.when_posted AS CommentPosted
    FROM Issues i
    LEFT JOIN 
        (SELECT issue, MAX(when_posted) AS LastPostDate 
         FROM comments GROUP BY issue) ic ON ic.issue = i.id
    LEFT JOIN Comment c ON c.issue = i.id AND c.when_posted = ic.LastPostDate  
    ORDER BY COALESCE(ic.LastPostDate, issues.when_opened) DESC