I need help with a SQL query in PHP ( WordPress ). I have this data:
| id | kw_id | date | position
| 1 | 1 | 2020.08.23 | 16 |
| 2 | 1 | 2020.10.02 | 17 |
| 3 | 2 | 2020.10.08 | 5 |
| 4 | 2 | 2020.10.08 | 6 |
and I need get two rows ( id=2, id=3 ). Query criteries is two:
when date have duplicate ( id=3 and id=4 ) then get row with min position.
id | kw_id | date | position
2 | 1 | 2020.10.02 | 17
3 | 2 | 2020.10.08 | 5
Thanks in advance.
If you are using MySQL 8+, then ROW_NUMBER
provides one option:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC, position) rn
FROM yourTable
)
SELECT id, kw_id, date, position
FROM cte
WHERE rn = 1;
The above call to ROW_NUMBER
puts the latest date first for each id
, and in the case of ties for date, puts the smallest position first.
For legacy MySQL 5.* it can be little complicated. Below query that returns needle id's:
select min(id) as min_id
from tbl
join (
select kw_id, max(date) max_date
from tbl
group by kw_id
) tbl1 on tbl1.max_date = tbl.date and tbl1.kw_id = tbl.kw_id
group by tbl.kw_id;
result:
+========+
| min_id |
+========+
| 2 |
+--------+
| 3 |
+--------+
and now final query:
select * from tbl where id in (
select min(id) as min_id
from tbl
join (
select kw_id, max(date) max_date
from tbl
group by kw_id
) tbl1 on tbl1.max_date = tbl.date and tbl1.kw_id = tbl.kw_id
group by tbl.kw_id
);
and final result:
+====+=======+============+==========+
| id | kw_id | date | position |
+====+=======+============+==========+
| 2 | 1 | 2020-10-02 | 17 |
+----+-------+------------+----------+
| 3 | 2 | 2020-10-08 | 5 |
+----+-------+------------+----------+
and here live SQL fiddle
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.