首页 > 解决方案 > MariaDB Select Distinct ON(预期有表达式(接近 ON)

问题描述

我正在尝试使用 Distinct On a Column 进行简单查询(因为我仍然想返回表中的所有其他列)但是当我尝试使用 ON (Column) 子句时,它一直显示错误“预期有一个表达式(接近开启)”

我不知道这条消息是什么意思,因为查询的格式似乎正确,这是 MariaDB 而不是 MySQL 特有的吗?

MariaDB 版本 10.3.28 如果这有什么用?

SELECT DISTINCT ON (No, Branch) *
FROM   Table1
ORDER  BY No, a DESC;

在此处输入图像描述

表格1

|    ID     |     No     |    Branch     |     Datetime     |

| --------- | ---------- | ------------- | ---------------- |

| 1         | 1          |  1            | 18/10/2021 10:00 |
| 2         | 1          |  1            | 19/10/2021 10:00 |
| 3         | 1          |  2            | 22/10/2021 10:00 |
| 4         | 1          |  2            | 20/10/2021 11:37 |
| 5         | 1          |  1            | 21/10/2021 10:00 |
| 6         | 1          |  1            | 22/10/2021 11:37 |
| 7         | 2          |  1            | 20/10/2021 10:00 |
| 8         | 2          |  1            | 22/10/2021 11:37 |

基本上我想在“No”和“Branch”上使用 Distinct 基本上给我 1 条记录,其中 No 和 Branch 是唯一的,并且它使用 MAX(Datetime)

我曾尝试使用 Group by 子句,但这给了我一行来自其他行的混合结果。

我追求的结果是:

|    ID     |     No     |    Branch     |     Datetime     | 
| --------- | ---------- | ------------- | ---------------- |
| 6         | 1          |  1            | 22/10/2021 11:37 |
| 3         | 1          |  2            | 22/10/2021 10:00 |
| 8         | 2          |  1            | 22/10/2021 11:37 |

我想显示表中的所有列,因为我还将根据 No 和 Branch 进行 Join 来获取 Name

标签: mysqlmariadbdistinct

解决方案


尝试:

CREATE TABLE table_tst (
  `ID` int(5),
  `No` int(5), 
  `Branch` int(5), 
  `Datetime` Datetime
);
    
INSERT INTO table_tst VALUES 
(1,1,1,'2021-10-18 10:00:00'),
(2,1,1,'2021-10-19 10:00:00'),
(3,1,2,'2021-10-22 10:00:00'),
(4,1,2,'2021-10-20 11:37:00'),
(5,1,1,'2021-10-21 10:00:00'),
(6,1,1,'2021-10-22 11:37:00'),
(7,2,1,'2021-10-20 10:00:00'),
(8,2,1,'2021-10-22 11:37:00');


   select * 
from table_tst where (No,Branch,Datetime) in 
(
select `No`,`Branch`,MAX(`Datetime`)  as max_time
from table_tst
group by `No`,`Branch`
)
order by No ,Branch ASC;

演示:https ://www.db-fiddle.com/f/vhqJXYFy52xRtVBc97R1EL/8

datetime是保留字mysqlhttps ://dev.mysql.com/doc/refman/8.0/en/keywords.html它应该是反引号或者我建议使用其他非保留字


推荐阅读