从每个 GROUP BY (unique_id) 和 ORDER BY 数字中选择具有 MAX id 的行

问题描述 投票:0回答:3

我有一个包含 id、unique_id 和 order_number 的表。

  1. 我想按 unique_id 对行进行分组
  2. 我想从每个组中获取具有 MAX id 的行
  3. 最后一件事我想按 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
mysql
3个回答
34
投票

您可以将查询用作子查询:

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

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;

0
投票

你可以用这个非常简单的方法

SELECT 
    id, MAX(unique_id) as unique_data, order_number
FROM
    table
WHERE final = 0 
AND username = '$username' 
AND active = 1 
GROUP BY unique_data
ORDER BY MAX(unique_data);
© www.soinside.com 2019 - 2024. All rights reserved.