MySQL - 执行此操作的最佳方法是什么

时间:2012-10-12 00:41:06

标签: mysql select distinct min

我的表格如下:

| ID | value |
|  0 |   5   |
|  1 |   2   |
|  0 |   1   |
|  1 |   6   |
|  2 |   3   |
|  2 |   8   |
|  1 |   2   |
|  0 |   1   |
|  2 |   4   |

我正在尝试将我的结果只接受一行id,其中value是所有列的min,例如:

SELECT DISTINCT * FROM table WHERE MIN(table.value) = table.value

我该如何解决?谢谢!

编辑:

我想要的输出是:

| ID | value |
|  0 |   1   | -> is the min of all the rows with id = 0
|  1 |   2   |
|  2 |   3   |

编辑2:

类似的东西:

SELECT DISTINCT *
FROM tableName AS A
WHERE value = (SELECT MIN(value) From tableName AS B WHERE A.ID=B.ID)

但是tableName是(SELECT * FROM ...........) ..我该怎么做?

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT ID, Value
FROM tableName
WHERE value = (SELECT MIN(value) From tableName)

SQLFiddle Demo

后续问题,如果同一个value具有相同的ID,则会出现什么情况,会显示哪条记录?

答案 1 :(得分:1)

这个怎么样:

SELECT DISTINCT a.ID, a.value
FROM tableName AS a
WHERE a.value = (SELECT MIN(b.value)
                 FROM tableName AS b
                 WHERE a.id = b.id)

答案 2 :(得分:0)

这就是你想要的

select id,min(value) from tableName group by id