mysql - 如何在 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 行。我不知道编码它。
解决方案
使用子查询测试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)
推荐阅读
- python - Python Selenium 查找具有动态 ID 的元素
- qtwebengine - 有什么方法可以实时转换来自 QWebEngine 的输出图像?
- sql - 如何修复在 SQL 中更新表时出现的错误?
- android - 在模块 jetified-play-services-places-9.2.1-runtime 中发现重复类 com.google.android.gms.location.places.zza
- google-cloud-platform - 在没有 JWT 令牌的情况下连接到 Google IoT
- tensorflow - 如何使用带有冻结特征层的 fast.ai 微调训练有素的模型?
- three.js - 在 ThreeJS 着色器上更改菲涅尔衰减
- html - 当我链接到 jquery 文件时,我还必须输入 type="text/javascript"
- javascript - TypeError: Cannot read properties of undefined (reading 'map') 似乎找不到函数的问题
- rabbitmq - 带有 RabbitMQ 插件的 ThingsBoard