【问题标题】:Confusing MySQL query令人困惑的 MySQL 查询
【发布时间】:2009-04-27 03:05:06
【问题描述】:

我有两张桌子,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' ) )

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您需要使用数据透视查询,类似于下面未经测试的代码:

    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(搜索“pivot”)。

    【讨论】:

      【解决方案2】:

      你不能这样做,因为你不能给列赋值。
      您必须进行 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';
      

      它会起作用,但您不会在一列中包含工作人员的家庭和手机号码。

      【讨论】:

        【解决方案3】:

        您需要加入电话表两次。

        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' )
        

        【讨论】:

          【解决方案4】:

          这就像我的通讯录的问题。

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

          【讨论】:

            猜你喜欢
            • 2013-03-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-30
            • 2022-01-21
            • 2022-01-17
            • 2018-02-26
            相关资源
            最近更新 更多