简体   繁体   中英

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.

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. I have no idea to code it.

Use a sub query to test the 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 for multiple columns is not supported. same column cant not print And order by id asc use and all record print 1 - n means minimum id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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