让我们说我在mysql数据库中有这样的表:
Id number version date
1 123 1 2016-01-12
2 123 2 2016-01-13
3 124 1 2016-01-14
4 124 2 2016-01-15
5 124 3 2016-01-16
6 125 1 2016-01-17
我想获取表格中的所有行,其中版本字段中的值是每个相应数字的最大值。例如,我想得到这个输出:
Id number version date
2 123 2 2016-01-13
5 124 3 2016-01-16
6 125 1 2016-01-17
我试过这样的事情:
SELECT * FROM myTable WHERE version = (SELECT MAX(version) FROM myTable)
但上述查询返回空。
请帮忙!
答案 0 :(得分:2)
使用此
select *
from myTable
natural join
(select max(version) as version, number from myTable group by number) as T;
答案 1 :(得分:1)
你可以在
中使用in子句和group原始版本
SELECT * FROM myTable
WHERE (version, number) in
(SELECT MAX(version), number FROM myTable group by number)
版本编辑
SELECT * FROM myTable
inner join myTable2 on myTable.id = myTable2.mytable_id
WHERE (version, number) in
(SELECT MAX(version), number FROM myTable group by number)
答案 2 :(得分:0)
这里有几个选项和小提琴。这些只会选择具有相关number
的最大版本的行。
select *
from releases r1
where version =
(
select max(version)
from releases
where number=r1.number
);
(fiddle) 这是一个(可能更好)版本:
select * from releases
where (version, number) in (
select max(version), number
from releases
group by number
);
答案 3 :(得分:-2)
此
的SQLFIDDLEhttp://sqlfiddle.com/#!9/a931fb/1
SELECT * FROM demo WHERE version = (SELECT MAX(version) FROM demo)
这很好用