[英]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.