[英]How to select all the last row of some column scope in MySQL
I need a query to select the last rows of some column scope. 我需要查询以选择某些列范围的最后一行。
Example, the whole table: 例子,整个表:
----------------------
| ID | NAME | FOO_ID |
|--------------------|
| 1 | jQue | 2 |
| 2 | Prot | 2 |
| 3 | Node | 2 |
| 4 | Moo | 1 |
| 5 | Scri | 1 |
----------------------
Rows returned by query, that returns all the "last row" in FOO_ID
column scope: 查询返回的行,返回FOO_ID
列范围内的所有“最后一行”:
----------------------
| ID | NAME | FOO_ID |
|--------------------|
| 3 | Node | 2 |
| 5 | Scri | 1 |
----------------------
Can someone help me in how to code this query? 有人可以帮我编码该查询吗?
SELECT a.*
FROM table_1 a
INNER JOIN (SELECT foo_id, max(id) as max_id FROM table_1 GROUP BY foo_id)b
ON b.max_id = a.id
I'd use whichever of these you find most clear: 我会使用其中最清晰的任何一个:
or 要么
SELECT *
FROM the_table
WHERE id IN
( SELECT MAX(id)
FROM the_table
GROUP
BY foo_id
)
;
or 要么
SELECT *
FROM the_table a
WHERE NOT EXISTS
( SELECT 1
FROM the_table b
WHERE b.foo_id = a.foo_id
AND b.id > a.id
)
;
or 要么
SELECT a.*
FROM the_table a
LEFT
OUTER
JOIN the_table b
ON b.foo_id = a.foo_id
AND b.id > a.id
WHERE b.id IS NULL
;
(My own preference is the version with IN
, but you may feel differently.) (我个人更喜欢使用IN
的版本,但是您可能会有所不同。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.