好的标题可能无法证明我在这里要做的事情,但是不能很好地解释我的问题,以便完美地解释它。
我正在尝试做什么:
我需要从MySQL数据库中检索响应= 8或9的行,但如果有多个匹配则显示最新的条目。假设我有6行,1行有响应= 8和2行,其中response = 9我想根据行ID检索最新的条目。
示例:
row1 id = 12 user_id = 15 response = 8
row2 id = 11 user_id = 15 response = 9
row3 id = 10 user_id = 15 response = 1
row4 id = 09 user_id = 15 response = 9
row5 id = 08 user_id = 15 response = 4
row6 id = 07 user_id = 15 response = 5
我想检索row1,因为它是response = 8或9
的最新条目我试过但失败了:
SELECT a.id, MAX(a.response) FROM user a WHERE a.user_id = $userID AND a.response IN (8,9) GROUP BY a.user_id
先谢谢。
答案 0 :(得分:0)
SELECT a.id, MAX(a.response) -- Your columns
FROM user a -- Table
WHERE a.user_id = $userID -- your ESCAPED parameters (see mysql prepared stmts)
AND a.response IN (8,9)
GROUP BY a.response
ORDER BY a.id DESC -- the greater the ID, the 'newer'
LIMIT 1 -- just get one record
答案 1 :(得分:0)
假设我已理解您的问题,并且您想要指定用户的最新行(即id
列中的最高值),但仅在响应为8或9的位置,请尝试
SELECT id
FROM user
WHERE user_id = $userID
AND response IN (8,9)
ORDER BY id DESC
答案 2 :(得分:0)
SELECT u.id, u.user_id, u.response
FROM user u
WHERE u.id in
(
SELECT max(id) FROM user WHERE user_id = $userID and response IN (8,9)
) ;
ID USER_ID RESPONSE
12 15 8