multiple joins, each with IN statement returns too many results

Mevia :

I am struggling with building mysql query so it returns right results. Idea is that i need to fetch data from main table but some of the fields are only references to other tables where also record exists in various languages.

so example code is:

SELECT cars.model
FROM cars
LEFT JOIN parts ON parts.id = cars.partId AND parts.language IN ('en', 'de')
LEFT JOIN interior ON interior.id = cars.interiorId AND interior.language IN ('en', 'de')
LEFT JOIN exterior ON exterior.id = cars.exteriorId AND exterior.language IN ('en', 'de')
LEFT JOIN wheels ON wheels.id = cars.wheelId AND wheels.language IN ('en', 'de')
LEFT JOIN extra ON extra.id = cars.extraId AND extra.language IN ('en', 'de')
WHERE cars.id IN ('72727272') AND cars.source = 1

What i need is two results from query (one in english and one in german), instead i am getting 24 results. They are in various configuration of languages.

I tried adding:

  • GROUP BY ... but its not working.
  • DISTINCT same as above

Maybe someone knows some tricks on how to deal with this kind of situation (at worst case i can execute query twice for each language but its extremely slow).

Uueerdo :

The problem you are experiencing is due to every match from parts, interior, exterior, and so on are being combined with each other regardless of language. You're getting every combination of the associated de and en data.

SELECT cars.model
FROM cars
CROSS JOIN (SELECT 'en' AS language UNION SELECT 'de') AS l
LEFT JOIN parts ON parts.id = cars.partId AND parts.language = l.language
LEFT JOIN interior ON interior.id = cars.interiorId AND interior.language = l.language
LEFT JOIN exterior ON exterior.id = cars.exteriorId AND exterior.language = l.language
LEFT JOIN wheels ON wheels.id = cars.wheelId AND wheels.language = l.language
LEFT JOIN extra ON extra.id = cars.extraId AND extra.language = l.language
WHERE cars.id IN ('72727272') 
   AND cars.source = 1

Also, I am assuming the full query you are attempting SELECTs more than just cars.model; otherwise, all this JOINing is pointless.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216338&siteId=1