How to remove duplicate rows from the output of multiple joins of MYSQL query?
I have 3 tables: Client, Purchase, Product
Client Table:
Cid | ClientName |
---|---|
1 | SAM |
2 | JOE |
Purchase Table:
PurchaseID | Cid | ProductID |
---|---|---|
1 | 1 | 1 |
2 | 1 | 2 |
3 | 2 | 1 |
Product Table:
ProductID | ProductName |
---|---|
1 | JAM |
2 | BREAD |
After inner joining them it should look like this: Output:
Cid | ClientName | ProductID | ProductName |
---|---|---|---|
1 | SAM | 1 | JAM |
1 | SAM | 2 | BREAD |
2 | JOE | 1 | JAM |
I tried the below query:
SELECT C.Cid, C.ClientName, Pr.ProductID, Pr.ProductName
FROM Client C
JOIN Purchase Pu
ON C.Cid = Pu.Cid
JOIN Product Pr
ON Pu.ProductID = Pr.ProductID
Even though I am getting the required results, there are many duplicates in all columns for some rows. Ex:
Cid | ClientName | ProductID | ProductName |
---|---|---|---|
1 | SAM | 1 | JAM |
1 | SAM | 1 | JAM |
How to remove one of the duplicate rows from the result?
You could add group by to have unique rows.
CREATE TABLE client(
cid INT,
client_name varchar(10) );
insert into client values
(1,'SAM'),
(2,'JOE'),
(1,'SAM');
CREATE TABLE purchase (
purchase_id INT,
cid INT,
product_id int );
insert into purchase values
(1,1,1),
(2,1,2),
(3,2,1);
CREATE TABLE product (
product_id INT,
product_name varchar(10) );
insert into product values
(1,'JAM'),
(2,'BREAD'),
(1,'JAM');
SELECT C.Cid, C.client_name, Pr.product_id, Pr.product_name
FROM client C
JOIN purchase Pu ON C.cid = Pu.cid
JOIN product Pr ON Pu.product_id = Pr.product_id
group by C.Cid, C.client_name, Pr.product_id, Pr.product_name;
Result:
cid client_name product_id product_name
2 JOE 1 JAM
1 SAM 1 JAM
1 SAM 2 BREAD
I added some duplicates values in the Demo to tell the difference. Demo