Mysql 从混合数据中获取唯一值的Sql查询
我是MySql新手,一直在为一个项目学习MySql。我有一个如下表(表1),我需要它的输出作为表2Mysql 从混合数据中获取唯一值的Sql查询,mysql,sql,database,select,relational-database,Mysql,Sql,Database,Select,Relational Database,我是MySql新手,一直在为一个项目学习MySql。我有一个如下表(表1),我需要它的输出作为表2 Table 1: Input Table +----+----------+-----+-----------+----------+ | ID | FRUIT_TYPE | FRUIT | CREATED_AT +----+----------+-----+-----------+----------+ | 1 | Drupes | plums |
Table 1: Input Table
+----+----------+-----+-----------+----------+
| ID | FRUIT_TYPE | FRUIT | CREATED_AT
+----+----------+-----+-----------+----------+
| 1 | Drupes | plums | 2020-06-12 25:10:10
| 2 | Drupes | peaches | 2020-06-11 25:10:10
| 3 | Drupes | olives | 2020-06-11 24:10:10
| 4 | Berries | grapes | 2020-06-08 25:10:10
| 5 | Pomes | apples | 2020-06-07 25:10:10
| 6 | Pomes | pears | 2020-06-05 25:10:10
| 7 | Hesperidia | lemons | 2020-06-05 24:10:10
| 8 | Hesperidia | oranges | 2020-06-05 23:10:10
+----+----------+-----+-----------+----------+
输出按CREATED_AT字段进行排序,如果同一水果类型有多行,则拾取具有最少CREATED_AT值的字段
例如,在核果的3个值中,只有1行是水果为橄榄的,创建的_AT值最小
如果发出sql查询,请务必进行解释:P
提前谢谢 一个简单的方法是相关子查询:
select t.*
from t
where t.created_at = (select min(t2.created_at)
from t t2
where t2.fruit_type = t.fruit_type
);
有了(水果类型,创建于)
上的索引,这可能也是最有效的方法
select t.*
from t
where t.created_at = (select min(t2.created_at)
from t t2
where t2.fruit_type = t.fruit_type
);