This question is an exact duplicate:
- I can not write the correct SQL query 1 response
Already the third hour I puzzle how to write the correct request, but nothing leaves.
The task is as follows:
There is a table of cars
auto (автомобили) id | name ------------- 1 | Volvo 2 | Audi 3 | Toyota There is a table of spare parts
spare (запчасти) id | name ------------- 1 | Колеса 2 | Двигатель 3 | Руль There are many to many table for connecting parts and cars
spare_to_auto auto_id | spare_id ------------------ 1 | 1 1 | 2 1 | 3 2 | 1 2 | 2 You need to get a list of cars whose parts list matches from two or more. And they need to be sorted in order of coincidence from large to small. Parts list is set by the user in the filter
That's what I got in the end
SELECT * FROM auto as a INNER JOIN spare_to_auto AS s_to_a ON a.id = s_to_a.auto_id INNER JOIN spare AS s ON s_to_a.spare_id = s.id AND s.id IN ($список_запчастей) GROUP BY a.id But unfortunately this request does not work correctly.
order by count(1) descjust gives sorting by the number of matches. so besides, what you wrote here is just such an order by add and everything - Mike