mysql - 令人困惑的 MySQL 查询

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

最佳答案

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

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/

相关文章:

mysql - 无法在 Solaris 10 中找到 mysql 实例

MySql join 语句返回重复数据

php - MySQL密码字段如何使用区分大小写?

mysql 查询 - 条件语句?

php - 查询获取树上的类别和产品

php - CakePHP 迁移数据库行

mysql - 多个连接成一列

php - 填补从数据库返回的日期中的空白 - 纯 SQL 解决方案可能吗?

php - WordPress - mysql_query() : Access denied for user 'www-data' @'localhost' (using password: NO) error on production server

python - SQLAlchemy:如何处理重复条目中的 bulk_save_objects()?