MySQL - 选择具有最小值的组

时间:2017-01-15 11:33:34

标签: mysql

我有一个包含以下数据的简单表格:

id | descr | val1 | val2
========================
1  | 'aa'  |  1   |  5
2  | 'bb'  |  2   |  7
3  | 'bb'  |  3   |  1
4  | 'bb'  |  4   |  19
5  | 'aa'  |  5   |  1
6  | 'aa'  |  6   |  8
7  | 'bb'  |  7   |  11
8  | 'bb'  |  8   |  3
9  | 'aa'  |  9   |  16
10 | 'aa'  |  10  |  9

我想为每个唯一descr选择最小值为val2的行。 预期结果:

id | descr | val1 | val2
========================
3  | 'bb'  |  3   |  1
5  | 'aa'  |  5   |  1

我尝试了以下查询:

SELECT *, min(val2) minVal FROM test group by descr

结果与最小值行中的数据无关:

id | descr | val1 | val2 | minVal
==================================
1  | 'aa'  |  1   |  5   |  1
2  | 'bb'  |  2   |  7   |  1

请告知。

谢谢

1 个答案:

答案 0 :(得分:5)

在MySQL中处理此问题的一种标准方法是使用子查询来识别每个nav.navbar .navbar-nav.mega .mega-menu li a { color: #d9d9d9; } nav.navbar .navbar-nav.mega .mega-menu li a { font-size: 16px; font-weight: 400; } a { color: #fd7339; text-decoration: none; background-color: transparent; } nav.navbar .navbar-nav.mega .mega-menu li:before { content: "\00BB"; padding-right: 5px; } *, *:hover, *:active { outline: 0 none; } *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } nav.navbar .navbar-nav.mega .mega-menu ul { list-style: none; padding-left: 0; } ul ul, ol ul, ul ol, ol ol { margin-bottom: 0; } nav.navbar .navbar-nav.mega .mega-menu { background-color: #454545; width: 1000px; min-height: 325px; left: -166px; z-index: 1; position: absolute; padding: 20px 50px; pointer-events: none; overflow: hidden; opacity: 0; visibility: hidden; -webkit-transition: opacity 0.2s ease-in-out; -moz-transition: opacity 0.2s ease-in-out; -o-transition: opacity 0.2s ease-in-out; transition: opacity 0.2s ease-in-out; } nav.navbar .navbar-nav.mega .mega-menu { width: 895px; } nav.navbar .navbar-nav.mega .mega-menu { background-color: #454545; width: 1000px; min-height: 325px; left: -166px; z-index: 1; position: absolute; padding: 20px 50px; pointer-events: none; overflow: hidden; opacity: 0; visibility: hidden; -webkit-transition: opacity 0.2s ease-in-out; -moz-transition: opacity 0.2s ease-in-out; -o-transition: opacity 0.2s ease-in-out; transition: opacity 0.2s ease-in-out; } 组的最小val2值,该方法不具有对分析函数的广泛支持。然后使用此子查询将descr的记录限制为您希望在结果集中显示的内容。

test

在这里演示:

SQLFiddle