我正在嘗試使用 Distinct On a Column 做一個簡單的查詢(因為我仍然想回傳表中的所有其他列)但是當我嘗試使用 ON(列)子句時,它一直顯示錯誤“預期有一個運算式(接近開啟)”
我不知道這條訊息是什么意思,因為查詢的格式似乎正確,這是 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 |
I would be wanting to to display all columns in the table, as i will also be doing a Join to fetch the Name based on No and Branch
uj5u.com熱心網友回復:
嘗試:
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,它應該在反引號中,或者我建議使用其他非保留字
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331491.html
