[英]Sql Query to obtain unique values from a mixed data
I am new to MySql and have been trying to learn it for a project.我是 MySql 的新手,并且一直在尝试为一个项目学习它。 I have a table as below (Table 1) and I need the output from it as Table 2.
我有一个如下表(表 1),我需要表 2 中的 output。
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
+----+----------+-----+-----------+----------+
The output is ordered by CREATED_AT field and if there are multiple rows for the same FRUIT_TYPE, the field with the least CREATED_AT value is picked. output 按 CREATED_AT 字段排序,如果同一 FRUIT_TYPE 有多行,则选择 CREATED_AT 值最小的字段。
For e..g of the 3 values for Drupes, only 1 row is taken where FRUIT is olives and the CREATED_AT values is the least.例如,在核果的 3 个值中,只取 1 行,其中 FRUIT 是橄榄,CREATED_AT 值最少。
If you put out the sql query, do explain it.如果您提出 sql 查询,请解释一下。 :P Thanks in advance !
:P 在此先感谢!
A simple method is a correlated subquery:一个简单的方法是相关子查询:
select t.*
from t
where t.created_at = (select min(t2.created_at)
from t t2
where t2.fruit_type = t.fruit_type
);
With an index on (fruit_type, created_at)
, this is likely to be the most performant method as well.使用
(fruit_type, created_at)
上的索引,这也可能是性能最高的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.