令人困惑的MySQL查询

时间:2009-04-26 18:52:36

标签: mysql

我有两个表,staffphones

Staff只有一个字段staff_idPhones有三个字段:staff_idphone_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' ) )

4 个答案:

答案 0 :(得分: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

注意 - 多次加入电话表也行,但上述解决方案应该表现更好,并且可以轻松扩展到其他phone.field_types。

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

答案 1 :(得分: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';

它会起作用,但你不会在一栏中有一个工作人员回家和手机号码。

答案 2 :(得分: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' )

答案 3 :(得分:1)

这就像我的地址簿问题一样。

你可以在这里找到答案: SQL Database problems with addressbook table design

相关问题