MySql:Group By选择特定值或最大值

时间:2014-03-28 03:52:48

标签: mysql

假设我有一个包含id和版本的表。我正在按ID分组。对于每个id,如果version = 2,则获取该行,否则获取MAX(版本)。

+----+---------+
| id | version |
+----+---------+
|  1 |       3 |
|  1 |       2 |
|  2 |       1 |
|  2 |       3 |
+----+---------+

应该获取

+----+---------+
| id | version |
+----+---------+
|  1 |       2 |
|  2 |       3 |
+----+---------+

查询应该是这样的:

select id, version(2 if exists for id or max) from table group by id;

我不想使用union,因为它实际上是一个带有多个连接的巨大查询。我只是用一个更简单的例子来说明问题。

可能的解决方案:

select * from (select * from table order by version = 2 desc, version desc) as t1 group by id

4 个答案:

答案 0 :(得分:1)

1.获取版本= 2的行;

2.获取id不在version = 2行中的最大版本行;

3.将它们分开。

试试这个:

SELECT id, version FROM table WHERE version = 2
UNION
SELECT id, MAX(version) version FROM table WHERE id not in 
(SELECT id FROM table WHERE version = 2)
GROUP BY id

SQL Fiddle

答案 1 :(得分:0)

试试这个

select id, version from table 
where id=2 or version in 
    (select max(version) from table 
        where id!=2  group by id)

答案 2 :(得分:0)

试试这个:

SELECT * FROM(SELECT id,versioin from table1 where version=2 
union 
SELECT id,max(version) as version FROM `table1 ` GROUP BY version) as A 
group by version

SELECT id,versioin from table1 where version=2 
union 
SELECT id,max(version) as version FROM `table1 ` 
where id not in(SELECT id from table1 where version=2 ) GROUP BY version 

答案 3 :(得分:0)

查看此处:

SELECT id,ver
FROM table1
WHERE ver = 
(SELECT MAX(ver) FROM table1 WHERE ver < (SELECT MAX(ver) FROM table1))
UNION
SELECT id,(MAX(`ver`)) FROM table1 WHERE id=2;

sqlfiddle:http://sqlfiddle.com/#!2/b7f65/1