Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql join gives duplicate rows

I have 2 tables and i am using join to get common records from those 2 tables. i have used the following query but my problem is i am getting the records doubled. The query is as follows

SELECT * FROM pos_metrics pm INNER JOIN pos_product_selling pps ON   
pm.p_id=pps.p_id WHERE pm.p_id='0' AND pps.pos_buying_id='0' AND pm.type=1

pos_metrics table:
enter image description here

pos_product_selling table: enter image description here

Output:

enter image description here

EDIT
When I tried to use GROUP BY and DISTINCT together I am not getting duplicates but the value from the second table is repeated. Any other solutions ?

like image 590
Deepak Avatar asked Jun 15 '11 02:06

Deepak


People also ask

Why is join duplicating rows?

In some cases, you need to join tables by multiple columns. In these situations, if you use only one pair of columns, it results in duplicate rows.

How prevent duplicate rows in SQL join?

Solution. Select column values in a specific order within rows to make rows with duplicate sets of values identical. Then you can use SELECT DISTINCT to remove duplicates. Alternatively, retrieve rows in such a way that near-duplicates are not even selected.

How do I prevent duplicate rows in MySQL?

You can use a PRIMARY KEY or a UNIQUE Index on a table with the appropriate fields to stop duplicate records. Let us take an example – The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name.


3 Answers

try this:

SELECT DISTINCT * FROM ...
GROUP BY pm.metrics
like image 40
nunu Avatar answered Sep 22 '22 14:09

nunu


Try something like these

GROUP BY pos_product_selling.metrics
like image 72
Jayakrishnan K Avatar answered Sep 20 '22 14:09

Jayakrishnan K


Add a primary key in the pos_metrics table and introduce it to the pos_product_selling table, then do a JOIN based on the primary key as well as the other criteria. You won't get these duplicates then.

The reason you have duplicates over here is because there is no possibility of an unique comparison to be done on both tables based on a value.

like image 20
Shyam Natraj Kanagasabapathy Avatar answered Sep 21 '22 14:09

Shyam Natraj Kanagasabapathy