使用SELECT - JOIN从同一个表中获取两个值

时间:2018-05-25 13:20:26

标签: mysql sql

我有三张桌子 - 材料,活动和单位。 通过包含unit_id属性,材料和活动表都与单元表相关。如何通过单个查询获取活动的单位和材料的单位?

这是我目前的查询:

SELECT u.username, m.name, a.name, un.name
FROM users u
JOIN materials m
ON (m.id = u.material_id)
JOIN activities a
ON (a.id = u.activity_id)
JOIN units un
ON (un.id = m.unit_id OR un.id = a.unit_id)

然而,我只收到一个单位,我希望获得材料的单位和活动的单位。我如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

两次加入units

SELECT u.username, 
       m.name as m_name, unm.name as m_unit,
       a.name as a_name, una.name as a_unit
FROM users u
JOIN materials m ON m.id = u.material_id
JOIN activities a ON a.id = u.activity_id
JOIN units unm ON unm.id = m.unit_id
JOIN units una ON una.id = a.unit_id

答案 1 :(得分:1)

你可以使用一个子查询,这对于这样的情况很方便:

SELECT u.username, 
       (SELECT name FROM m WHERE m.id = u.material_id), 
       (SELECT name FROM a WHERE a.id = u.activity_id)
   FROM users