I need help with following query.
I have 4 tables:
+------------+------------+--------------+-----------------+
| project | motor | component | motor_component |
+------------+------------+--------------+-----------------+
| project_id | motor_id | component_id | mc_id |
| name | project_id | name | motor_id |
| | name | | component_id |
+------------+------------+--------------+-----------------+
I need to create query that return matrix 'Component is use in MOTOR X':
+----------------+---------+---------+---------+-----+---------+
| component.name | MOTOR 1 | MOTOR 2 | MOTOR 3 | ... | MOTOR X |
+----------------+---------+---------+---------+-----+---------+
| Flange | 1 | | | | |
| Shaft | | 1 | | | |
+----------------+---------+---------+---------+-----+---------+
In rows I need component name and 1 in columns MOTOR * when this component is in this motor for specyfic project (only one project in query).
I have query that return result for statics motor_id and for static quantity of motors (and static project_id, but this is not a problem):
SELECT c.name
,CASE WHEN EXISTS (SELECT i.name
FROM component i
JOIN motor_component_ i_mc
ON i.component_id = i_mc.component_id
WHERE i.component_id = c.component_id
AND i_mc.id_motor = 7
)
THEN '1'
ELSE NULL
END AS 'MOTOR 1'
,CASE WHEN EXISTS (SELECT i.name
FROM component i
JOIN motor_component_ i_mc
ON i.component_id = i_mc.component_id
WHERE i.component_id = c.component_id
AND i_mc.id_motor = 12
)
THEN '1'
ELSE NULL
END AS 'MOTOR 2'
FROM component c
JOIN motor_component mc
ON c.component_id = mc.component_id
JOIN motor m
ON mc.motor_id = m.motor_id
JOIN project p
ON m.project_id = p.project_id
WHERE p.project_id = 30
I don't know how to create dynamic query for unknown motors quantity and unknown motor_ids I don't know is it possible after all.