MySql 分组但仍显示所有行

MySql Group by but still show all rows

我有以下数据库

ID imagename testresult sampleref uploadedat orderid
1 filename1.png NULL ABC123 2021-08-19 12:00 1002
2 filename2.png NULL ABC123 2021-08-19 13:00 1001
3 filename3.png NULL ABC123 2021-08-19 14:00 1002
4 filename4.png NULL ABC123 2021-08-19 15:00 1001

我正在使用 SQL 查询

SELECT * 
FROM results 
WHERE imagename IS NOT NULL 
  AND testresult IS NULL 
  AND sampleref LIKE 'LAT%' 
ORDER BY testresult IS NULL DESC, uploadedat 
LIMIT 25

但是我想按 orderid 分组(而不是聚合分组),这样结果将显示为

ID imagename testresult sampleref uploadedat orderid
1 filename1.png NULL ABC123 2021-08-19 12:00 1002
3 filename3.png NULL ABC123 2021-08-19 14:00 1002
2 filename2.png NULL ABC123 2021-08-19 13:00 1001
4 filename4.png NULL ABC123 2021-08-19 15:00 1001

这里我们最初按 uploadedat 排序,但随后显示匹配 orderid 的其余结果,本质上将它们分组在一起,但仍显示每一行。

我不能使用 ORDER BY orderid, uploadedat,因为这会将第 2 行和第 4 行置于第 1 行和第 3 行之上

解决这个问题的方法是什么?它是否使用 2 个 select 语句,第一个 selecting * 与 orderid 和 orderby uploadedat 分组,然后第二个没有分组,其中 orderid = $Row['orderid']?或者有没有办法在单个语句中为此执行 JOIN 或 double Select?

谢谢?

使用

ORDER BY orderid desc,uploadedat asc

在 mysql 8.0

中测试
with cte as
(
select 1002 as id ,'2021-08-19 12:00' as upd
union all
select 1002 as id ,'2021-08-19 14:00' as upd
union all
select 1001 as id ,'2021-08-19 13:00' as upd
union all
select 1001 as id ,'2021-08-19 15:00' as upd
) select * from cte order by id desc,upd asc

Demo

您想首先按每个 orderid 的最小值 uploadedat 排序。

如果你的 MySql 版本是 8.0+ 你可以使用 MIN() window 函数:

SELECT * 
FROM results
WHERE imagename IS NOT NULL 
  AND testresult IS NULL 
ORDER BY MIN(uploadedat) OVER (PARTITION BY orderid),
         uploadedat

对于以前的版本使用相关子查询:

SELECT r1.* 
FROM results r1
WHERE r1.imagename IS NOT NULL 
  AND r1.testresult IS NULL 
ORDER BY (SELECT MIN(r2.uploadedat) FROM results r2 WHERE r2.orderid = r1.orderid),
         r1.uploadedat

参见demo