[英]How to select one row each conditions in MySQL?
我的代碼有麻煩。 我想在MySQL中每個條件僅獲得一行。
我有一張這樣的桌子:
ID - Position - Content
1 2 abc
2 1 def
3 1 ghk
4 3 pol
5 2 lop
6 4 gty
所以我希望返回的結果是:position = 1->最高ID行,然后傳遞到position = 2->最高ID行。 我不知道編碼。
使用子查詢測試ID
drop table if exists t;
create table t
(ID int, Position int, Content varchar(3));
insert into t values
(1 , 2 , 'abc'),
(2 , 1 , 'def'),
(3 , 1 , 'ghk'),
(4 , 3 , 'pol'),
(5 , 2 , 'lop'),
(6 , 4 , 'gty');
select t.*
from t
where t.id = (select min(id) from t t1 where t1.position = t.position);
+------+----------+---------+
| ID | Position | Content |
+------+----------+---------+
| 1 | 2 | abc |
| 2 | 1 | def |
| 4 | 3 | pol |
| 6 | 4 | gty |
+------+----------+---------+
4 rows in set (0.00 sec)
您可以嘗試如下查詢
SELECT t.*
FROM t
WHERE t.id IN (SELECT min(id) FROM t GROUP BY position);
試試這個查詢..
SELECT DISTINCT * FROM table-name ORDER BY ID ASC;
DISTINCT在單列上運行。 不支持多列的DISTINCT。 同一列無法打印,並且按ID升序使用ID並使用所有記錄打印命令1-N表示最小ID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.