mysql - 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
解决方案
尝试:
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
是保留字mysql
:https ://dev.mysql.com/doc/refman/8.0/en/keywords.html它应该是反引号或者我建议使用其他非保留字
推荐阅读
- html - 在我的 getStepContent 方法中显示一个文本框
- java - 快捷方式添加到 Android 主屏幕
- python - 我如何在 python 中创建一个 SQLite3 数据库,以便任何人都可以看到它的内容并从他们的计算机上访问它?
- sql-server - Web API 上的 NUnit 集成测试 - 如何创建/销毁集成测试数据库
- css - 使用 BeautifulSoup 抓取 ::before ::after CSS 伪元素的网页内容
- javascript - 为数组和对象扩展 immutable.is
- javascript - 数据表过滤数字大于
- java - 将朋友列表实现到数据库中的最佳方法?MySQL
- angular - 使用 Material select 和 routerLink,Angular 6 路由页面
- php - 十月 CMS - 允许管理员用户仅编辑一条记录