MySQL join获取最后一个有效行

时间:2013-10-01 18:09:47

标签: mysql join

我有两张桌子:

用户

id  |  email
1   |  email1@test.com
2   |  email2@test.com

和问题

id  |  userId  |  isValid  | status
1   |  1       |  0        | pending
2   |  1       |  1        | processed

我想做一个MySQL查询,返回所有具有最新有效问题的用户(即questions.isValid = 1,questions.id是该用户最高的)。我在“最新”部分磕磕绊 - 这是迄今为止的查询(返回所有有效问题)。

SELECT u.email, q.status
FROM users AS u
LEFT JOIN questions AS q ON u.id = q.userId
WHERE q.isValid = 1
ORDER BY u.id ASC

有什么建议吗? stackoverflow上有很多类似的问题,但我找不到一个精确匹配该问题的问题。谢谢!

编辑:感谢所有答案!我忘了提一件重要的事情:如果该用户没有有效的问题,我仍然希望用户在结果中显示,状态=''。

4 个答案:

答案 0 :(得分:3)

Mmmkay,这个怎么样?

http://www.sqlfiddle.com/#!2/b6d65/1

SELECT u.email, q.status
FROM users AS u

LEFT JOIN (

  ( SELECT MAX(mq.id) AS id
    FROM questions AS mq
    WHERE mq.isValid = 1
    GROUP BY mq.userId
  ) AS maxq

  INNER JOIN questions AS q ON q.id = maxq.id

) ON u.id = q.userId

ORDER BY u.id ASC

答案 1 :(得分:1)

    SELECT u.email, CASE q.status WHEN q.isValid=1 THEN q.status ELSE q.STATUS='' end as status
FROM users AS u
LEFT JOIN questions AS q ON u.id = q.userId
WHERE  q.id IN(SELECT MAX(id) maxid FROM questions GROUP BY userid)
ORDER BY u.id ASC

http://www.sqlfiddle.com/#!2/003dd/12

答案 2 :(得分:1)

如果你想要最新的状态,这将有效:

SELECT   u.email,
         (SELECT status FROM questions WHERE userId = u.id ORDER BY id DESC LIMIT 1) status

FROM     users AS u

答案 3 :(得分:1)

这里是您的查询:

SELECT u.email,q.status
FROM users AS u
LEFT JOIN question AS q ON u.id = q.userId
WHERE  q.id = (SELECT max(id) from question where isvalid = 1 and userid = u.id )
GROUP BY q.isValid,u.id

检查演示here