首页 > 解决方案 > 如何在 MySQL 中每个条件选择一行?

问题描述

我的代码有问题。我想在 MySQL 中每个条件只得到一行。

我有一张这样的桌子:

ID - Position  - Content
1       2         abc
2       1         def
3       1         ghk
4       3         pol
5       2         lop
6       4         gty

所以我希望返回的结果如下:位置 = 1 -> 最高 id 行然后传递给位置 = 2 -> 最高 id 行。我不知道编码它。

标签: mysqlsql

解决方案


使用子查询测试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)

推荐阅读