Sun Z Sun Z - 19 days ago 6
MySQL Question

LEFT JOIN query returning double results

Good evening,

I am using a LEFT JOIN to query atable and btable, but when I run the query, I get back each result twice. (Only when I have duplicates)

My Query is as follow:

$sql="
SELECT *
FROM atable A
LEFT JOIN btable B ON (A.article_number = B.article_number)
WHERE A.article_number2 = B.article_number2
";


atable

Name id name article_number article_number2
Row1 1 Mercedes M1 M2


btable

Name id name article_number article_number2
Row1 1 Mercedes M1 M2
Row2 2 Mercedes M1 M2


Acually I should get this results:


Mercedes: 1x

Mercedes: 1x


I get this:


Mercedes: 1x

Mercedes: 1x

Mercedes: 1x

Mercedes: 1x


Am I missing something?

Any help will be appreciated.
Thanks in advance.

Answer

Your SQL is all most correct you just need to add GROUP BY into your sql query.

SELECT *
FROM atable as A
LEFT JOIN btable as B ON (A.article_number = B.article_number)
WHERE A.article_number2 = B.article_number2
GROUP BY A.id

Here A.id is a primary_key of your table atable.

Hope this works for you :)