简体   繁体   English

如何在MySQL中的每个条件下选择一行?

[英]How to select one row each conditions in MySQL?

I have a trouble with my code. 我的代码有麻烦。 I want to get only one rows each conditions in MySQL. 我想在MySQL中每个条件仅获得一行。

I have a table like that: 我有一张这样的桌子:

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

So I want the result returned like: position = 1 -> highest id row then pass to position = 2 -> highest id row. 所以我希望返回的结果是:position = 1->最高ID行,然后传递到position = 2->最高ID行。 I have no idea to code it. 我不知道编码。

Use a sub query to test the 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)

you can try like below query 您可以尝试如下查询

SELECT t.*
FROM t
WHERE t.id IN (SELECT min(id) FROM t GROUP BY position);

try this query.. 试试这个查询..

 SELECT DISTINCT * FROM table-name ORDER BY ID ASC;

DISTINCT operates on a single column. DISTINCT在单列上运行。 DISTINCT for multiple columns is not supported. 不支持多列的DISTINCT。 same column cant not print And order by id asc use and all record print 1 - n means minimum id 同一列无法打印,并且按ID升序使用ID并使用所有记录打印命令1-N表示最小ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM