3

我有 2 张桌子:

用户

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

4 回答 4

3

嗯,这个呢?

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
于 2013-10-01T18:25:39.937 回答
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

于 2013-10-01T18:18:34.170 回答
1

如果您只想要最新状态,这将起作用:

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

FROM     users AS u
于 2013-10-01T18:18:48.187 回答
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

在这里查看演示

于 2013-10-01T18:30:11.473 回答