繁体   English   中英

Sql 查询从混合数据中获取唯一值

[英]Sql Query to obtain unique values from a mixed data

我是 MySql 的新手,并且一直在尝试为一个项目学习它。 我有一个如下表(表 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
+----+----------+-----+-----------+----------+

output 按 CREATED_AT 字段排序,如果同一 FRUIT_TYPE 有多行,则选择 CREATED_AT 值最小的字段。

例如,在核果的 3 个值中,只取 1 行,其中 FRUIT 是橄榄,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)上的索引,这也可能是性能最高的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM