gpt4 book ai didi

MYSQL 查询与选择具有 LIMIT 条件不同

转载 作者:行者123 更新时间:2023-12-01 00:35:26 24 4
gpt4 key购买 nike

目前,我有一个如下表,我想提取具有 estimated_date 的 id 的记录,这些记录被分配给 update_index 值的最小值,如果该值为空,我想将值分配给下一个 update_index,

例如,用于记录

  • id=73,我想获取2017-06-13 00:00:00这个值
  • id=75,我想获取2017-01-01 00:00:00的值
  • id=76,我想获取2018-06-01 00:00:00的值

输入表

+----+--------------+---------------------+
| id | update_index | estimated_date |
+----+--------------+---------------------+
| 73 | 1 | 2017-06-13 00:00:00 |
+----+--------------+---------------------+
| 73 | 2 | 2017-01-13 00:00:00 |
+----+--------------+---------------------+
| 73 | 3 | 2017-05-13 00:00:00 |
+----+--------------+---------------------+
| 73 | 4 | NULL |
+----+--------------+---------------------+
| 75 | 1 | 2017-01-01 00:00:00 |
+----+--------------+---------------------+
| 75 | 2 | NULL |
+----+--------------+---------------------+
| 75 | 3 | 2019-01-01 00:00:00 |
+----+--------------+---------------------+
| 76 | 1 | NULL |
+----+--------------+---------------------+
| 76 | 2 | 2018-06-01 00:00:00 |
+----+--------------+---------------------+

输出表

+----+--------------+---------------------+
| id | update_index | estimated_date |
+----+--------------+---------------------+
| 73 | 1 | 2017-06-13 00:00:00 |
+----+--------------+---------------------+
| 75 | 1 | 2017-01-01 00:00:00 |
+----+--------------+---------------------+
| 76 | 2 | 2018-06-01 00:00:00 |
+----+--------------+---------------------+

我已经尝试了以下值,但我总是只得到一条记录,你能帮我解决这个问题吗?

SELECT  id,update_index,estimated_date
FROM tablename where estimated_date = (
SELECT DISTINCT estimated_date
FROM tablename
where estimated_date is not null
ORDER BY id, udpate_index ASC
LIMIT 1);
`

最佳答案

我会使用相关子查询:

select t.*
from tablename t
where t.update_index = (select t2.update_index
from tablename t2
where t2.id = t.id and t2.estimated_date is not null
order by t2.update_index asc
limit 1
);

关于MYSQL 查询与选择具有 LIMIT 条件不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com