0

您好,我正在寻求有关我的查询的帮助,该查询当前运行没有错误,但也没有显示我需要的数据。我的表存储电话号码,相关字段是 id、phonetype 和 phonenumber。

运行时它返回列id, HOME PHONE, WORK PHONE,CELL PHONE尽管它只显示最后一个数字。假设在给定的行中有一个家庭电话和一个工作电话号码......我只在该 ID 的工作电话列中获取数据。如果连续有一个家庭电话、工作电话和一个手机......我只在 CELL PHONE 列中获取数据。

我需要按电话类型在唯一列中为给定 ID 的所有电话号码中的一行。我希望这是有道理的,如果不是,查询应该让您知道我在寻找什么...谢谢

SELECT id,
(IF(phonetype = 'HOME PHONE', phonenumbers.phonenumber, '')) AS 'HOME PHONE',
(IF(phonetype = 'WORK PHONE', phonenumbers.phonenumber, '')) AS 'WORK PHONE',
(IF(phonetype = 'CELL PHONE', phonenumbers.phonenumber, '')) AS 'CELL PHONE'
FROM phonenumbers
GROUP BY id;

我正在查询的表看起来像这样

id | name | phonetype | phonenumber

1  |  Jim  |  HOME PHONE | 0000000001        
1  |  Jim  |  WORK PHONE | 0000000002
2  |  Kim  |  HOME PHONE | 0000000003
2  |  Kim  |  WORK PHONE | 0000000004
2  |  Kim  |  CELL PHONE | 0000000005

我正在寻找的结果看起来像这样......

id | name | home phone | work phone | cell phone

 1 | Jim | 0000000001 | 0000000002 | 
 2 | Kim | 0000000003 | 0000000004 | 0000000005
4

1 回答 1

1

假设每个 ID 对应的每种类型只有一个电话号码:

SELECT a.id,
(SELECT phonenumbers.phonenumber FROM phonenumbers WHERE phonetype = 'HOME PHONE' AND id = a.id) AS 'HOME PHONE',
(SELECT phonenumbers.phonenumber FROM phonenumbers WHERE phonetype = 'WORK PHONE' AND id = a.id)  AS 'WORK PHONE',
(SELECT phonenumbers.phonenumber FROM phonenumbers WHERE phonetype = 'CELL PHONE' AND id = a.id)  AS 'CELL PHONE'
FROM phonenumbers a
GROUP BY a.id;

可能有帮助。干杯。

于 2013-04-03T22:42:42.797 回答