Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Joining two tables without duplicates?

Tags:

mysql

I have two tables that I am trying to join. One contains a list of customers, the other is a list of orders. I am trying to formulate a query that will allow me to select all of the customers listed in the table customers who have at least one order in the table orders. However, I do not want to get duplicates for those customers who have multiple orders. Any suggestions how I can accomplish this?

I know this is probably a common issue, however I have no idea what this type of query would be called so that I could search for an answer. Any suggestions would be greatly appreciated. Thanks.

like image 530
Wige Avatar asked Jan 27 '11 17:01

Wige


2 Answers

It's much simpler than you may think:

select distinct(customer_id) from orders;

Edit: If you actually want to get the full info on the customer,

select * from customers where customer_id in (select distinct(customer_id) from orders);

like image 195
Michael Kopinsky Avatar answered Oct 19 '22 14:10

Michael Kopinsky


Use:

SELECT c.*
  FROM CUSTOMERS c
 WHERE EXISTS (SELECT NULL
                 FROM ORDERS o
                WHERE o.custeromid = c.id)

The IN clause is an alternative, but EXISTS works better for duplicates because it returns true on the first duplicate so it doesn't process the entire table.

like image 24
OMG Ponies Avatar answered Oct 19 '22 15:10

OMG Ponies