[英]MySql: Group By Select specific value or max
lets say I have a table with id and version. 可以说我有一个ID和版本表。 I am grouping by id.
我正在按ID分组。 For each id, if version = 2, then fetch that row else fetch MAX(version).
对于每个id,如果version = 2,则获取该行,否则获取MAX(version)。
+----+---------+
| id | version |
+----+---------+
| 1 | 3 |
| 1 | 2 |
| 2 | 1 |
| 2 | 3 |
+----+---------+
Should fetch 应该获取
+----+---------+
| id | version |
+----+---------+
| 1 | 2 |
| 2 | 3 |
+----+---------+
Query should be something like: 查询应类似于:
select id, version(2 if exists for id or max) from table group by id;
I would prefer not to use union since it's a huge query in reality with multiple joins. 我宁愿不使用工会,因为这实际上是具有多个联接的庞大查询。 I just used a simpler example to get the point across.
我只是用一个简单的例子来说明这一点。
Possible Solution: 可能的解决方案:
select * from (select * from table order by version = 2 desc, version desc) as t1 group by id
1.Fetch rows that version=2; 1.获取版本为2的行;
2.Fetch max version rows that id not in version=2 rows; 2.获取不在版本= 2行中的id的最大版本行;
3.Unionize them. 3.Unionize他们。
And try this: 尝试一下:
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
Try this 尝试这个
select id, version from table
where id=2 or version in
(select max(version) from table
where id!=2 group by id)
Try this: 尝试这个:
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
or 要么
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
look here: 看这里:
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 sqlfiddle: http ://sqlfiddle.com/#!2/b7f65/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.