2

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

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

我试图进行子选择,但它也不起作用。

感谢任何答案。

4

2 回答 2

4

在这里,您需要有一个子查询,它date_add为每个id_orderon table获取最新信息ps_order_history。然后,子查询的结果将连接回原始表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
于 2013-04-02T13:10:43.220 回答
3

要获得最后日期,您需要加入:

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

您的 having 子句计算最大日期,然后在它不等于 0 时成功(大多数情况下)。

于 2013-04-02T13:11:09.647 回答