2009-04-26 91 views
1

我有两个表,staffphones混淆MySQL查询

Staff只有一个字段staff_idPhones有三个字段:staff_id,phone_typenumber

我想显示所有员工的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')) 

回答

1

您不能这样做,因为您无法将值分配给列。
你就必须做2联接:

SELECT staff.staff_id, cells.number, home.number FROM staff 
    JOIN phones AS cells ON (...) 
    JOIN phones AS home ON (...) 
    WHERE cells.field_type='Cell' AND home.field_type='Home'; 

它的工作,但你不会有工作人员家庭和手机号码,在一列。

1

您需要加入电话表两次。

SELECT staff.staff_id, cellPhones.number, homePhones.number, 
FROM staff 
LEFT JOIN phones cellPhones ON (staff.staff_id = phones.staff_id && phones.field_type = 'Cell') 
LEFT JOIN phones homePhones ON (staff.staff_id = phones.staff_id && phones.field_type = 'Home') 
2

你需要使用一个支点查询,如下面的未经测试的代码的东西:

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.field_types。

另请参阅http://dev.mysql.com/doc/refman/5.1/en/select.html(搜索“数据透视表”)。