如何使用ORDER和LIMIT MySql进行左连接

时间:2013-12-14 17:59:41

标签: mysql left-join

我有一个提取门票的sql,我需要在上次回复时间和最后回复中加入

但是这个sql仍在为1张票提取多个回复,我只需要最后一个

SELECT a.*,
r.lastreply_by,
r.lastreplytime
FROM  `tickets` AS a
LEFT JOIN replies AS r ON a.id = (SELECT r.ticketid ORDER BY ticketid DESC LIMIT 1)

这是从那个sql的快照 http://prntscr.com/2b4ihy

任何帮助表示赞赏。 谢谢!

3 个答案:

答案 0 :(得分:1)

你可以这样试试

SELECT t.*,
       r.lastreply_by,
       r.lastreplytime
  FROM tickets t LEFT JOIN 
(
    SELECT ticketid, lastreply_by, lastreplytime
      FROM
    (
        SELECT ticketid, lastreply_by, lastreplytime
          FROM replies 
         ORDER BY lastreplytime DESC
    ) q
     GROUP BY ticketid
) r
    ON t.id = r.ticketid

这是 SQLFiddle 演示

答案 1 :(得分:1)

假设replyidreplies表中每个回复的唯一键:

SELECT 
    a.*,
    r.lastreply_by,
    r.lastreplytime
FROM  
    `tickets` a
        LEFT JOIN (
            SELECT ticketid t, MAX(replyid) replyid
            FROM
                replies
            GROUP BY ticketid
        ) t ON t.t = a.ticketid
        LEFT JOIN replies r ON r.ticketid = t.t AND r.replyid = t.replyid

ps:这是标准的SQL,因此它为peter的答案提供了一个很好的替代方案(当然不会降低它的有效性。)

答案 2 :(得分:1)

这应该有效:

SELECT a.*,
r.lastreply_by,
r.lastreplytime
FROM  `tickets` AS a
LEFT JOIN replies AS r
ON r.id = (
  SELECT r2.id
  FROM replies r2
  WHERE r2.ticketid = a.id
  ORDER BY r2.lastreplytime DESC
  LIMIT 1
)

编辑:我将订单更改为lastreplytime,因此它实际上会返回最新回复。

SQL小提琴:http://sqlfiddle.com/#!2/1f5c16/4