MySQL - 查询返回客户的第一个订单

时间:2011-12-01 12:09:37

标签: mysql

基本架构(仅显示相关字段):

客户

id  |  fname  |  sname  |  email

订单

order_id  |  customer  |  level  |  timestamp

我需要选择每个客户,但是我希望加入他们的个人详细信息,以加入他们第一个订单的level

SELECT c.fname, c.sname, c.email, o.level
FROM customers c
LEFT JOIN orders o ON c.id = o.customer

..?

修改

到目前为止,我尝试了两种解决方案,它们完全杀死了我的整个数据库。运行查询后,没有数据库请求会完成,所以我想知道查询是否太大。大约有10,000个订单和15,000个客户。这是预期的吗?我之前从未遇到过这些问题。

5 个答案:

答案 0 :(得分:1)

尝试此查询 -

SELECT c.fname, c.sname, c.email, o.level FROM customers c
  LEFT JOIN (
    SELECT o1.* FROM orders o1
      JOIN (SELECT customer, MIN(timestamp) timestamp FROM orders GROUP BY customer) o2
        ON o1.customer = o2.customer AND o1.timestamp = o2.timestamp) o
    ON c.id = o.customer;

答案 1 :(得分:1)

嗯,这会起作用,但不是最佳的:

SELECT c.fname, c.sname, c.email, o.level
FROM customers c
LEFT JOIN orders o ON c.id = o.customer
WHERE o.`timestamp` = ( SELECT MIN( o1.`timestamp` ) FROM orders o1 WHERE o1.customer = c.id ) 
GROUP BY c.id

答案 2 :(得分:0)

SELECT c.fname, c.sname, c.email, o.level
FROM customers c
LEFT JOIN orders o ON c.id = o.customer
ORDER BY o.timestamp ASC LIMIT 1

答案 3 :(得分:0)

SELECT c.fname, c.sname, c.email, o.level
FROM customers c
LEFT JOIN orders o ON c.id = o.customer
ORDER BY o.timestamp
GROUP BY c.id

答案 4 :(得分:0)

子选择绝对不是最有效的,但这是一个查询

SELECT c.fname, c.sname, c.email, o.level, 
    (select level from orders 
    where c.id = o.customer order by timestamp asc limit 0,1) as level
FROM customers c

这将为您提供所有客户(订单与否)及其相应级别。如果性能很慢,请确保您也有适当的索引