2016-07-29 59 views
0

我有一个表结构抓取最大值行明智在MySQL

ID Col_1 col_2 col_3 col_4 
1 34  23  45  32 
2 20  19  67  18 
3 40  10  76  86 

我在这里想从COL_1,col_,col_3,col_4所以我的输出看起来像

ID Col_1 col_2 col_3 col_4 max 
    1 34  23  45  32 45 
    2 20  19  67  18 67 
    3 40  10  76  86 86 

我的最大值尝试使用

SELECT ID, MAX(col_1,col_2,col_3,col_4) as max 
FROM demo 
GROUP BY ID 

任何帮助将不胜感激。

+0

什么是查询的结果你写的吗? – Thijs

回答

1

您需要规范化表结构。试试这个

select ID, max(Col_1) as max_value from 
(
select ID, Col_1 from table 
union all 
select ID, Col_2 from table 
union all 
select ID, Col_3 from table 
union all 
select ID, Col_4 from table 
) as t group by ID 
+0

这个作品像魅力!由于 – Deepesh

1

你可能会尝试这个

SELECT ID, col_1, col_2, col_3, col_4, 
GREATEST(col_1, col_2, col_3, col_4) AS max_value FROM table_name 
+0

谢谢!!! ......它的工作原理 – Deepesh

0

@Thijs给您参考,这是对应的输出I得到。通过@Madhivanan第一次查询的

enter image description here

查询结果

enter image description here

从最初的两种解决方案的查询结果提供