我有id,unique_id和order_number的表.
我也有几个WHERE条款.这是我的尝试不起作用:
SELECT MAX(id) AS id
, order_number
FROM table
WHERE final = 0
AND username = '$username'
AND active = 1
GROUP
BY unique_id
ORDER
BY order_number
Run Code Online (Sandbox Code Playgroud)
Gio*_*sos 21
您可以将查询用作子查询:
SELECT *
FROM table
WHERE id IN (SELECT MAX(id) AS id
FROM table
WHERE final=0 AND username='$username' AND active=1
GROUP BY unique_id)
ORDER BY order_number
Run Code Online (Sandbox Code Playgroud)
或者,如果id不是唯一的,请使用JOIN:
SELECT t1.*
FROM table AS t1
JOIN (SELECT MAX(id) AS max_id, unique_id
FROM table
WHERE final=0 AND username='$username' AND active=1
GROUP BY unique_id
) AS t2 ON t1.unique_id = t2.unique_id AND t1.id = t2.unique_id
ORDER BY order_number
Run Code Online (Sandbox Code Playgroud)