gpt4 book ai didi

mysql - 如何使用 MySQL 选择父/子关系的最后一行匹配条件的最后一行

转载 作者:行者123 更新时间:2023-11-29 03:11:35 26 4
gpt4 key购买 nike

我的问题类似于 previous poster .

他的问题是:“仅使用 MySQL 我想选择父子关系的每个最后子行,其中子行按时间戳排序”。

我想这样做,但我也想只选择 status 为 1 的子行。

我的表是 fobs_inventoryfobs_inventory_history。我想要每个 fobs_inventory 的最新(即:最近时间戳)fobs_inventory_history 记录,其中 fobs_inventory_history.status = 1

-------------------------------
| fobs_inventory |
-------------------------------
| inv_id | other fields |
-------------------------------
| 1 | ... |
| 2 | ... |
| 3 | ... |
-------------------------------

----------------------------------------------
| fobs_inventory_history |
----------------------------------------------
| id | inv_id | status | created_at |
----------------------------------------------
| 1 | 1 | 0 | 2011-10-11 10:00:00 |
| 2 | 1 | 1 | 2011-08-01 10:00:00 |
| 3 | 1 | 0 | 2011-07-01 10:00:00 |

| 4 | 2 | 1 | 2011-09-11 14:00:00 |
| 5 | 2 | 0 | 2011-08-01 12:00:00 |
| 6 | 2 | 2 | 2011-07-01 00:00:00 |

| 7 | 3 | 1 | 2011-10-11 14:00:00 |
| 8 | 3 | 2 | 2011-08-01 12:00:00 |
| 9 | 3 | 0 | 2011-07-01 00:00:00 |
----------------------------------------------

生成类似于下表的结果集的最佳 SQL 语法是什么?

--------------------------------------------------------------------
| inv_id | fob_inventory_history_id | status | created_at |
--------------------------------------------------------------------
| 2 | 4 | 1 | 2011-09-11 14:00:00 |
| 3 | 7 | 1 | 2011-10-11 14:00:00 |
--------------------------------------------------------------------

我只想返回那些最近时间戳的 status 为 1 的行。

编辑

在进一步研究之后,我想出了解决方案,我将其发布在这里,因为它可能会帮助其他人尝试做同样的事情。

基本上解决方案是在子选择之外选择与 MAX() 和 GROUP BY 关联的所有对应字段,检查一下:

select h.id, h.fob_id, h.inv_id, h.status, h.created_at from fobs_inventory_history h, (
select id, inv_id, status, max(created_at) as ts
from fobs_inventory_history
group by inv_id
) h2
where h.created_at = h2.ts
and h.inv_id = h2.inv_id
and h.fob_id = 1 and h.status = 1

最佳答案

非常感谢您发帖!!解决了困扰我两天的问题。我需要包含一些父信息,因此我向该查询添加了一个 JOIN,如下所示:

select i.custid, i.custorderno, h.id, h.fob_id, h.inv_id, h.status, h.created_at from fobs_inventory_history h, (
select id, inv_id, status, max(created_at) as ts
from fobs_inventory_history
group by inv_id
) h2
INNER JOIN invoice AS i ON h2.inv_id = i.inv_id
where h.created_at = h2.ts
and h.inv_id = h2.inv_id
and h.fob_id = 1 and h.status = 1

关于mysql - 如何使用 MySQL 选择父/子关系的最后一行匹配条件的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7430402/

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