MySQL查询将规范化数据转换为单行

标签 mysql sql

我正在尝试创建查询以将规范化表格中的内容格式化为单行。

我想要的是这样的,每个联系人只有一行:

Name               Mobile            Office          Home
---------------    -----------       ----------      ----------
Fred Flintstone    123-456-7890      234-567-8901    789-012-3456  
Barney Rubble      456-789-0123                      678-901-2345
Wilma Flintstone   567-890-1234                      789-012-3456

我从最近的查询中得到的是这样的,每个联系人有多行:

Name               Phone           Phone_Type
---------------    ------------    -----------
Fred Flintstone    123-456-7890    Mobile
Fred Flintstone    234-567-8901    Office
Fred Flintstone    789-012-3456    Home
Barney Rubble      456-789-0123    Mobile
Barney Rubble      678-901-2345    Home
Wilma Flintstone   567-890-1234    Mobile
Wilma Flintstone   789-012-3456    Home

以下是涉及的表格(已简化):

contacts
----------
contact_id
name

link_contact_phonenumbers
-------------------------
contact_id
phone_number_id

phone_numbers
-------------
phone_number_id
phone_number
type_id

ref_phone_types
---------------
type_id
name

这是我目前所拥有的:

SELECT 
    cn.name as Name,
    concat( left(ph.phone_number,3) , "-" , mid(ph.phone_number,4,3) , "-", right(ph.phone_number,4)) as Phone,
    pt.name as Phone_Type
FROM
    contacts cn
    LEFT JOIN link_contact_phonenumbers lp ON lp.contact_id = cn.contact_id
    LEFT JOIN phone_numbers ph ON ph.phone_number_id = lp.phone_number_id
    LEFT JOIN ref_phone_types pt ON pt.type_id = ph.type_id

我查看了使用 GROUP_CONCAT() 函数,但这会将所有内容拉到一个列中。我需要他们进入自己的专栏。

我一直在研究子查询与 IF() 的结合,但还没有弄明白。

有没有办法在纯 SQL 中执行此操作?

最佳答案

听起来你可以通过一些连接来完成你正在寻找的东西:

Select a.name, c.phone_number, d.phone_number, e.phone_number from contacts a 
    left join link_contact_phonenumbers b on a.contact_id = b.contact_id 
    left join phone_numbers c on b.phone_number_id = c.phone_number_id and c.type_id = "whatever id is mobile"
    left join phone_numbers d on b.phone_number_id = d.phone_number_id and d.type_id = "whatever id is office"
    left join phone_numbers e on b.phone_number_id = e.phone_number_id and e.type_id = "whatever id is home"

我不知道这是否是最有效的方法,我现在也没有可以测试的数据库,所以它可能会关闭,但它应该为您指明正确的方向。还可能必须按 a.name 分组,以防第一个连接添加多行。

关于MySQL查询将规范化数据转换为单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24687277/

相关文章:

sql - 在非聚集索引中,第二、第三、第四...列如何排序?

mysql - 带有内连接的 SQL max()

java - 通过hibernate动态创建和切换数据库

php - 根据行值输出自定义消息

mysql - SQL 帮助,按另一个表分组

添加行时出现 PHP 错误

php - MySQL datetime 如何用 php 设置它

sql - sql如何将一张表的数据导入到另一张表

PHP PDO 动态 WHERE 子句

sql - 删除SQL中的相似列