gpt4 book ai didi

mysql - 按具有 max(date_field) 的 id 分组

转载 作者:行者123 更新时间:2023-11-29 01:17:11 25 4
gpt4 key购买 nike

要构建报告,我必须选择一些关于我所有客户的最后交易状态的信息。到目前为止,这是我得到的:

SELECT c.firstname, c.lastname, d.product_name, o.payment, s.name, h.date_add
FROM ps_orders o
INNER JOIN ps_order_detail d ON d.id_order = o.id_order
INNER JOIN ps_customer c ON c.id_customer = o.id_customer
INNER JOIN ps_order_history h ON o.id_order = h.id_order
INNER JOIN ps_order_state_lang s ON s.id_order_state = h.id_order_state
WHERE s.id_lang =6
GROUP BY c.id_customer
HAVING MAX(h.date_add)

对于每个客户,此查询在我需要最后一个日期时选择第一个日期(字段 h.date_add)。看来 MySQL 忽略了 HAVING

我试着做一个子选择,但它也不起作用。

感谢任何回答。

最佳答案

在这里,您需要有一个子查询,它为表 ps_order_history 上的每个 id_order 获取最新的 date_add。然后将子查询的结果连接回原始表 ps_order_history,前提是它处理两列:date_addid_order

SELECT  c.firstname, 
c.lastname,
d.product_name,
o.payment,
s.name,
h.date_add
FROM ps_orders o
INNER JOIN ps_order_detail d ON d.id_order = o.id_order
INNER JOIN ps_customer c ON c.id_customer = o.id_customer
INNER JOIN ps_order_history h ON o.id_order = h.id_order
INNER JOIN
(
SELECT id_order, MAX(date_add) max_date
FROM ps_order_history
GROUP BY id_order
) x ON h.id_order = x.id_order AND
h.date_add = x.max_date
INNER JOIN ps_order_state_lang s ON s.id_order_state = h.id_order_state
WHERE s.id_lang =6
GROUP BY c.id_customer

关于mysql - 按具有 max(date_field) 的 id 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15764935/

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