Answer the question
In order to leave comments, you need to log in
Merging 3 tables and fetching data without duplication?
Hello!
Guys, actually the question is the following.
There are 3 tables.
cities - cities
kladr_id - unique city key
manager_cities - cities that are assigned to the manager
manager_id - user ID from the managers table
kladr_id - from the cities
managers table - manager data table
manager_id - manager's unique key
The point is that one manager can work in several cities and I need to display on the page with a list of all managers - their data. It turns out the table for display should be:
Name | Phone number | Cities)
Please help me write a request to select a name, phone number and all the cities that are assigned to the manager. Simple JOINs are not suitable, because I get duplicate manager data if multiple cities are assigned to it.
Answer the question
In order to leave comments, you need to log in
SELECT `m`.`name`, `m`.`phone`, IFNULL(`t`.`cities`, '')
FROM (
SELECT `mc`.`manager_id` AS `manager_id`,
GROUP_CONCAT(`c`.`name`) AS `cities`
FROM `manager_cities` AS `mc`
JOIN `cities` AS `c` ON `c`.`kladr_id` = `mc`.`kladr_id`
GROUP BY `mc`.`manager_id`
) AS `t`
RIGHT JOIN `managers` AS `m` ON `m`.`manager_id` = `t`.`manager_id`
Yes, just JOIN will not help here, you need to group the results, and concatenate the field with the city:
SELECT managers.Имя, managers.Номер_телефона, GROUP_CONCAT(cities.Город) as Город(а)
FROM managers
JOIN manager_cities USING(manager_id)
JOIN cities USING(kladr_id)
GROUP BY managers.manager_id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question