Mysql子查询:试图从客户那里获得最后一个订单

时间:2010-01-19 14:42:51

标签: sql mysql subquery

抱歉,也许这是微不足道的,但我无法找到办法:

表客户

  • customer_id
  • CUSTOMER_EMAIL
  • customer_newsletter(1 =是/ 0 =否)

表格订单

  • ORDER_ID
  • CUSTOMER_ID
  • order_status(1 = ok / 0 = no_ok)

每个客户可以拥有零个,一个或多个订单。

我正在尝试查询以获取以下人员的所有电子邮件:

1 /尚未成为客户,他们从未下过订单,但他们希望收到我的简报

2 /已经是客户(相应表中的一个或多个订单)。 但只有当他们最新订单的状态正常时 (我不想将通讯发送给有问题的客户)

我已经尝试了几种基于具有MAX功能的子查询,但找不到好的配方

有什么建议吗? 提前谢谢

4 个答案:

答案 0 :(得分:1)

1)

select *
from customers c
where customer_newsletter = 1 and
not exists ( select * from orders o where c.customer_id = o.customer_id )

2)

select *
from customers c
where 1 = ( select order_status from orders o1 
       where o1.customer_id = c.customer_id and 
             o1.order_id = ( select max(order_id) 
                             from orders o2 where o2.customer_id = c.customer_id)
     )

答案 1 :(得分:1)

假设您可以使用最新的订单ID作为最新订单ID,我认为应该可行:

SELECT c.customer_email
FROM customers c
LEFT OUTER JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_newsletter = 1 AND o.customer_id IS NULL
UNION
SELECT c.customer_email
FROM customers c
WHERE customer_id IN 
  (SELECT customer_id FROM orders WHERE order_id IN 
    (SELECT MAX(order_id) FROM orders WHERE order_status = 1 GROUP BY customer_id)
  )

答案 2 :(得分:0)

SELECT  customer_email
FROM    customers c
WHERE   customer_newsletter
        AND COALESCE(
        (
        SELECT  order_status
        FROM    orders o
        WHERE   o.customer_id = c.customer_id
        ORDER BY
                o.customer_id DESC, o.date_purchased DESC
        LIMIT 1
        ), 1)

orders (customer_id, date_purchased)上创建一个索引,以便快速运行。但是,即使没有索引,它也能正常工作。

如果您希望成功的客户收到电子邮件而不管其简报设置如何,请使用以下命令:

SELECT  customer_email
FROM    customers c
WHERE   COALESCE(
        (
        SELECT  order_status
        FROM    orders o
        WHERE   o.customer_id = c.customer_id
        ORDER BY
                o.customer_id DESC, o.date_purchased DESC
        LIMIT 1
        ), customer_newsletter)

答案 3 :(得分:0)

为了让没有订单的客户想要您的简报,您可以使用LEFT OUTER JOIN。

示例(未经测试):

select c.*
from customers c left outer join orders o
on c.customer_id = o.customer_id
where (o.customer_id is null) and customer_newsletter = 1
order by c.customer_id