2009-04-26 149 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(搜索「數據透視表」)。