可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
To build a report, I must select some information on the last transaction status of all my customers. Until now, this is what I got:
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)
For each customer, this query is selecting the first date (the field h.date_add) when I need of the last one. It seems the MySQL is ignoring the HAVING.
I tried to make a sub-select, but it doesn't work too.
Thanks any answer.
回答1:
Here, you need to have a subquery which gets the latest date_add
for every id_order
on table ps_order_history
. The result of the subquery is then joined back on the original table ps_order_history
provided that it macth on two columns: date_add
and id_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
回答2:
To get the last date, you need to join it in:
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 inner join (select o.id_customer, max(oh.date_add) as maxdate from ps_order_history h join ps_order o on h.id_order = o.id_order group by o.id_customer) omax on omax.id_customer = o.id_customer and o.date_add = omax.maxdate WHERE s.id_lang =6 GROUP BY c.id_customer
Your having clause calculates the maximum date and then succeeds when it is not equal to 0 (which would be most of the time).