简体   繁体   English

左侧联接上的MySQL LIMIT

[英]MySQL LIMIT on a LEFT JOIN

My query: 我的查询:

   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

My problem with it is the "LIMIT 1" on the third line. 我的问题是第三行上的“ LIMIT 1”。 That limits all comments to only the newest one, so only issues with the newest comment will be reported back as having a comment at all. 这样会将所有评论都限制为最新评论,因此只有最新评论的问题才被报告为有评论。

If I removed the "LIMIT 1" part from there, I'd get a row for every comment in an issue, and that's not what I want. 如果我从那里删除了“ LIMIT 1”部分,那么问题中的每条评论都会出现一行,那不是我想要的。 What I want is only the newest comment for each issue. 我想要的只是每个问题的最新评论。

In any case, I'm not sure if my IFNULL part even works because that's not where I'm up to in debugging yet. 无论如何,我不确定我的IFNULL部分是否还能工作,因为这还不是我调试的重点。

So how would I achieve what I wanted? 那么我将如何实现我想要的呢?

Try: 尝试:

   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
   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

Edit 编辑

Since MySql does not have CTE's after all, try this: 由于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM