2016-03-08 63 views
4

我擁有帶id,unique_id和order_number的表。從每個GROUP BY(unique_id)和ORDER BY編號選擇具有MAX ID的行

  1. 我通過UNIQUE_ID
  2. 我想借此從每個組
  3. 而最後一件事,我想那種由ORDER_NUMBER行

我也有MAX ID行希望將行幾個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 
+0

''redni_broj'與'unique_id'相同嗎? – Strawberry

+0

GROUP GROUP by unique_id ... hmmm – Mihai

+0

對不起,我已編輯帖子。它應該是order_number – user3100193

回答

12

您可以使用查詢作爲子查詢:

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 

,或者如果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 
+1

或者可能只是'WHERE(id,unique_id)IN(SELECT MAX(id),unique_id FROM ...'在後一種情況下。 –

+0

我不明白這是如何工作的,但它的確如此! – fungusanthrax

2

試試這個:

SELECT id, redni_broj 
FROM table 
WHERE final=0 AND username='$username' AND active=1 AND 
    id IN (
       SELECT MAX(id) FROM table table2 
       WHERE table.unique_id = table2.unique_id 
     ) 
GROUP BY unique_id 
ORDER BY order_number;