简体   繁体   English

MySQL联接无重复

[英]MySQL Join Without Duplicates

I have a customers table, and an orders table. 我有一个客户表和一个订单表。 Each customer can have many orders. 每个客户可以有很多订单。

I want to select every customer, along with their earliest order number from the orders table (it is important that I select the earliest order number, not just any order). 我想从订单表中选择每个客户及其最早的订单号(重要的是选择最早的订单号,而不仅仅是任何订单)。 I want to list customers whether they have an order or not, and I don't want to include customers twice if they have more than one order. 我想列出客户是否有订单,如果客户有多个订单,我不想两次包含客户。

I'm using this: 我正在使用这个:

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

This gives me almost what I want, except it will pick whatever order ID it likes from the table. 几乎给了我想要的东西,除了它会从表中选择喜欢的任何订单ID。 I need to be able to sort, and pick the smallest order ID. 我需要能够排序,并选择最小的订单ID。

Any ideas please? 有什么想法吗?

Im pretty sure its something that's staring me in the face... 我很确定这是让我盯着我的脸...

EDIT: Tables' Structures as requested 编辑:表的结构按要求

  • Customers: 顾客:


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


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

Create a virtual table (a/k/a subquery) with the lowest numerical order ID for each customer. 为每个客户创建具有最低数字订单ID的虚拟表(a / k / a子查询)。

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

Then join that table with the customer table, like so. 然后将该表与客户表连接起来,就像这样。

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

Try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM