我有两个表,staff
和 phones
。
Staff
只有一个字段,staff_id
。 Phones
包含三个字段:staff_id
、phone_type
和number
。
我想显示所有员工的staff_id、手机号码和家庭电话号码。但我不知道如何将手机号码和家庭电话号码作为结果中的单独列。到目前为止,这是我一直在尝试的方法,它将两种类型的数字放在同一列中。
SELECT staff.staff_id, phones.number
FROM staff
LEFT JOIN phones ON ( staff.staff_id = phones.staff_id && ( phones.field_type = 'Cell' || phones.field_type = 'Home' ) )
最佳答案
您需要使用数据透视查询,类似于下面未经测试的代码:
select staff.staff_id,
MAX(IF(phones.field_type='Cell', phones.number, null)) as Cell,
MAX(IF(phones.field_type='Home', phones.number, null)) as Home
from staff,
phones
where phones.staff_id = staff.staff_id
group by staff.staff_id
注意 - 多次加入 phones 表也可以,但上面的解决方案应该执行得更好,并且可以轻松扩展以用于其他 phones.field_types。
另见 http://dev.mysql.com/doc/refman/5.1/en/select.html (搜索“枢轴”)。
关于mysql - 令人困惑的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/791376/