gpt4 book ai didi

mysql - 仅获取具有 5 个表的最大值的行

转载 作者:行者123 更新时间:2023-11-28 23:37:10 25 4
gpt4 key购买 nike

我有这个问题:

SELECT work_orders.id,work_orders.create_datetime,work_orders.location,
work_orders.description,user_accounts.function as function,
user_accounts.name as username,work_order_states.name as state,
work_orders_history.state_id,max(work_order_states.id)
FROM `work_orders`
LEFT JOIN work_orders_history
on work_orders.id = work_orders_history.work_order_id
LEFT JOIN user_accounts
on work_orders.create_user_id = user_accounts.id
LEFT JOIN work_order_type
on work_orders_history.type_id = work_order_type.id
LEFT JOIN work_order_states
on work_orders_history.state_id = work_order_states.id

... 结果是这样的: enter image description here

但我想要的只是获取最大 state_id 的行。

我已经尝试过各种查询,但这是我能得到的最好结果。

编辑:由于结果超过 65k,因此很难提供 fiddle 。理想的结果就像这张图片: enter image description here

提前致谢。

最佳答案

您的查询看起来非常接近。您需要添加一个 GROUP BY 并删除您选择的列之一。

SELECT work_orders.id,work_orders.create_datetime,work_orders.location,
work_orders.description,user_accounts.[function] as [function],
user_accounts.name as username,work_order_states.name as state,
max(work_order_states.id)
FROM `work_orders`
LEFT JOIN work_orders_history
on work_orders.id = work_orders_history.work_order_id
LEFT JOIN user_accounts
on work_orders.create_user_id = user_accounts.id
LEFT JOIN work_order_type
on work_orders_history.type_id = work_order_type.id
LEFT JOIN work_order_states
on work_orders_history.state_id = work_order_states.id

GROUP BY work_orders.id,work_orders.create_datetime,work_orders.location,
work_orders.description,user_accounts.function,
user_accounts.name,work_order_states.name
HAVING work_orders_states.ID = (SELECT MAX(state_id) FROM work_orders_history)

关于mysql - 仅获取具有 5 个表的最大值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463309/

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