我有一张这样的桌子:
+----+-------+---------+--------+--------+
| id | meta1 | meta2 | value1 | value2 |
+----+-------+---------+--------+--------+
| 1 | foo | bar | 0.1 | 0.01 |
| 1 | baz | quux | 0.2 | 0.01 |
| 1 | lorem | ipsum | 0.1 | 0.05 |
| 2 | dolor | sit | 0.2 | 0.02 |
| 2 | amet | eos | 0.3 | 0.02 |
| 3 | clita | corpora | 0.5 | 0.03 |
+----+-------+---------+--------+--------+
我试图为每个id提取一个(完整的)行,最小值为
value1
,如果存在相等的value1
s,则返回到最小值2。查询应产生如下结果集:
+----+-------+---------+--------+--------+
| id | meta1 | meta2 | value1 | VALUE2 |
+----+-------+---------+--------+--------+
| 1 | foo | bar | 0.1 | 0.01 |
| 2 | dolor | sit | 0.2 | 0.02 |
| 3 | clita | corpora | 0.5 | 0.03 |
+----+-------+---------+--------+--------+
我首先尝试以下查询:
SELECT
t1.*
FROM
test t1
INNER JOIN
(SELECT
id, MIN(value1) minValue1
FROM
test
GROUP BY id) t2 ON t1.id = t2.id
AND t1.value1 = t2.minValue1;
但这并没有打破id“1”的平局,我最终得到了其中两个记录。我试过添加HAVING子句和其他子查询,但在最初的步骤之后就丢失了。非常感谢您的帮助。
最佳答案
您需要所有记录,其中没有更好的记录(例如,具有较低值1或相同值1和更低值2)存在:
select *
from mytable
where not exists
(
select *
from mytable better
where better.id = mytable.id
and
(
better.value1 < mytable.value1
or
(better.value1 = mytable.value1 and better.value2 < mytable.value2)
)
);
关于mysql - 从组中选择两个值中的最小值作为单个结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31877978/