MySQL:如何对每个组中的数据进行排序?
我有一张这样的桌子:MySQL:如何对每个组中的数据进行排序?,mysql,sql,greatest-n-per-group,Mysql,Sql,Greatest N Per Group,我有一张这样的桌子: | Key | Value | Message | |-----|-------|---------| | a | 1 | xx | | a | 2 | yy | | b | 5 | mm | | b | 4 | nn | 我想按键对数据进行分组,得到每组的最小值以及相关消息。 预期结果是: | Key | Value | Message | |-----|-------|------
| Key | Value | Message |
|-----|-------|---------|
| a | 1 | xx |
| a | 2 | yy |
| b | 5 | mm |
| b | 4 | nn |
我想按键对数据进行分组,得到每组的最小值以及相关消息。
预期结果是:
| Key | Value | Message |
|-----|-------|---------|
| a | 1 | xx |
| b | 4 | nn |
我正在使用MySQL 5.7。可以这样做吗?您可以在下面尝试-
select * from tablename a
where value = (select min(value) from tablename b where a.key=b.key)
你可以在下面试试-
select * from tablename a
where value = (select min(value) from tablename b where a.key=b.key)
您可以使用
行编号()
:
如果排名功能不支持,您也可以使用相关的子查询
:
select t.*
from table t
where t.value = (select min(t1.value) from table t1 where t1.key = t.key);
您可以使用
行编号()
:
如果排名功能不支持,您也可以使用相关的子查询
:
select t.*
from table t
where t.value = (select min(t1.value) from table t1 where t1.key = t.key);
在MySQL 5.7或更早版本中处理此问题的规范方法是连接到一个子查询,该子查询为每个键查找最小值:
SELECT t1.`Key`, t1.`Value`, t1.Message
FROM yourTable t1
INNER JOIN
(
SELECT `Key`, MIN(`Value`) AS min_value
FROM yourTable
GROUP BY `Key`
) t2
ON t1.`Key` = t2.`Key` AND t1.`Value` = t2.min_value
ORDER BY
t1.`Key`;
请尽量避免使用保留的SQL关键字命名列和其他数据库对象,例如
Key
和Value
。你可以考虑将MySQL查询中的回退类型设为反模式。 < P>在MySQL 5.7或更早的时候处理这个问题的规范方法是加入一个子查询,该子查询为每个键找到最小值:
SELECT t1.`Key`, t1.`Value`, t1.Message
FROM yourTable t1
INNER JOIN
(
SELECT `Key`, MIN(`Value`) AS min_value
FROM yourTable
GROUP BY `Key`
) t2
ON t1.`Key` = t2.`Key` AND t1.`Value` = t2.min_value
ORDER BY
t1.`Key`;
请尽量避免使用保留的SQL关键字命名列和其他数据库对象,例如
Key
和Value
。您可以考虑在MySQL查询中键入反模式作为反模式的必要性。< P>首先创建一个子查询,该子查询返回<代码>最小值< /代码>每个代码>键/代码>,然后与主表连接:
select t.*
from tablename t
inner join (
select key, min(value) min_value
from tablename
group by key
) i on i.key = t.key and i.min_value = t.value
首先创建一个子查询,为每个
键
返回最小值
,然后与主表联接:
select t.*
from tablename t
inner join (
select key, min(value) min_value
from tablename
group by key
) i on i.key = t.key and i.min_value = t.value
使用此查询
select * from table_name tab1
where value in ( select MIN(value) from table_name tab2
where tab2.[key] = tab1.[key] )
使用此查询
select * from table_name tab1
where value in ( select MIN(value) from table_name tab2
where tab2.[key] = tab1.[key] )
这回答了你的问题吗?这回答了你的问题吗?