MySQL加入没有重复

时间:2012-06-13 12:18:49

标签: mysql join left-join

我有一个客户表和一个订单表。每个客户都可以有很多订单。

我想从订单表中选择每个客户以及他们最早的订单号(重要的是我选择最早的订单号,而不仅仅是任何订单)。我想列出客户是否有订单,如果客户有多个订单,我不想再包含两次。

我正在使用它:

  SELECT *
    FROM customers
    LEFT JOIN orders
    ON customers.id = orders.customer_id 
    GROUP BY customers.id

这给了我几乎我想要的东西,除了它会从表中选择它喜欢的任何订单ID。我需要能够排序,并选择最小的订单ID。

有什么想法吗?

我很确定它的某些东西正在盯着我......

编辑:根据要求提供表格结构

  • 客户:


    | ID | Name | Address            | Etc |
    ----------------------------------------
    | 1  | Joe  | 123 Fake Street    |     |
    | 2  | Mike | 1600 Fake Road     |     |
    | 3  | Bill | Red Square, Moscow |     |
    ----------------------------------------
    
  • 订单:


    | ID | Customer_ID | Date |
    ---------------------------
    | 1  | 1           |  ... |
    | 2  | 2           |  ... |
    | 3  | 2           |  ... |
    | 4  | 1           |  ... |
    ---------------------------
    

2 个答案:

答案 0 :(得分:5)

为每个客户创建一个具有最低数字订单ID的虚拟表(a / k / a子查询)。

SELECT customer_id, min(order_id)
  FROM orders
 GROUP BY customer_id

然后将该表与customer表连接起来,就像这样。

SELECT C.customer_id, firstorder.order_id
  FROM CUSTOMERS as C
  LEFT JOIN (
    SELECT customer_id, min(order_id)
      FROM orders
     GROUP BY customer_id
  ) AS firstorder ON c.customer_id = firstorder.customer_id

答案 1 :(得分:0)

试试这个

Select customer.*,Order.OrderNo As EarilerORderNo
From Customers Left Join 
(Select customer_id,orderid from orders order by customer_id,orderid desc) As Orders 
ON Customers.Id=Orders.OrderID