首页 > 解决方案 > Sql 查询从表中检索数据

问题描述

如何从表中检索奇数行?

在 Base 表中,Cr_id 总是重复 2 次。 基表

我想要一个仅检索那些 c_id =1 的 SELECT 语句,其中 Cr_id 始终是第一个,如输出表中所示。 输出表

只需查看基表和输出表,您应该会自动知道我想要什么,谢谢。

标签: mysqlsql

解决方案


只需测试最小日期就足够了

drop table if exists t;
create table t(c_id int,cr_id int,dt date);
insert into t values
(1,56,'2020-12-17'),(56,56,'2020-12-17'),
(1,8,'2020-12-17'),(56,8,'2020-12-17'),
(123,78,'2020-12-17'),(1,78,'2020-12-18');

select c_id,cr_id,dt
from t
where c_id = 1 and
        dt = (select min(dt) from t t1 where t1.cr_id = t.cr_id);

+------+-------+------------+
| c_id | cr_id | dt         |
+------+-------+------------+
|    1 |    56 | 2020-12-17 |
|    1 |     8 | 2020-12-17 |
+------+-------+------------+
2 rows in set (0.002 sec)

推荐阅读