Sql 查询以从混合数据中获取唯一值
Sql Query to obtain unique values from a mixed data
我是 MySql 的新手,一直在尝试为一个项目学习它。我有一个 table 如下所示 (Table 1) 我需要它的输出为 Table 2.
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
+----+----------+-----+-----------+----------+
Table 2: Final Output Desired
+----+----------+-----+-----------+----------+
| ID | FRUIT_TYPE | FRUIT | CREATED_AT
+----+----------+-----+-----------+----------+
| 3 | Drupes | olives | 2020-06-11 24:10:10
| 4 | Berries | grapes | 2020-06-08 25:10:10
| 6 | Pomes | pears | 2020-06-05 25:10:10
| 8 | Hesperidia | oranges | 2020-06-05 23:10:10
+----+----------+-----+-----------+----------+
输出按 CREATED_AT 字段排序,如果同一个 FRUIT_TYPE 有多行,则选择具有最小 CREATED_AT 值的字段。
例如,在核果的 3 个值中,只有 1 行是水果,CREATED_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
);
对于 (fruit_type, created_at)
上的索引,这也可能是性能最高的方法。
我是 MySql 的新手,一直在尝试为一个项目学习它。我有一个 table 如下所示 (Table 1) 我需要它的输出为 Table 2.
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
+----+----------+-----+-----------+----------+
Table 2: Final Output Desired
+----+----------+-----+-----------+----------+
| ID | FRUIT_TYPE | FRUIT | CREATED_AT
+----+----------+-----+-----------+----------+
| 3 | Drupes | olives | 2020-06-11 24:10:10
| 4 | Berries | grapes | 2020-06-08 25:10:10
| 6 | Pomes | pears | 2020-06-05 25:10:10
| 8 | Hesperidia | oranges | 2020-06-05 23:10:10
+----+----------+-----+-----------+----------+
输出按 CREATED_AT 字段排序,如果同一个 FRUIT_TYPE 有多行,则选择具有最小 CREATED_AT 值的字段。
例如,在核果的 3 个值中,只有 1 行是水果,CREATED_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
);
对于 (fruit_type, created_at)
上的索引,这也可能是性能最高的方法。