从多个表中获取电话号码的名称?

时间:2011-04-18 15:25:19

标签: mysql sql multiple-tables phone-number

我有这个表:

inbox table
SenderNumber Message

contact table
Name Number

district table
id SpvName Number

sub_district table
id district_id SpvName Number

village table
id sub_district_id SpvName Number

我想根据收件箱中的SenderNumber列从contact,district,sub_district或village获取名称或spvname。我如何实现这一目标?结果可能是这样的

SenderNumber | Name | Type         | Message  
-------------+------+--------------+------------
123          | john | contact      | bla bla  
234          | mary | district spv | bla bla bla  
提前谢谢,抱歉我的英语不好。

2 个答案:

答案 0 :(得分:3)

SELECT i.SenderNumber,
       COALESCE(c.Name, d.SpvName, sd.SpvName, v.SpvName) as Name,
       CASE WHEN c.Name IS NOT NULL THEN 'contact'
            WHEN d.SpvName IS NOT NULL THEN 'district'
            WHEN sd.SpvName IS NOT NULL THEN 'sub_district'
            WHEN v.SpvName IS NOT NULL THEN 'village'  
            ELSE ''
       END AS Type,
       i.Message
    FROM inbox i
        LEFT JOIN contact c
            ON i.SenderNumber = c.Number
        LEFT JOIN district d
            ON i.SenderNumber = d.Number
        LEFT JOIN sub_district sd
            ON i.SenderNumber = sd.Number   
        LEFT JOIN village v
            ON i.SenderNumber = v.Number   

答案 1 :(得分:0)

这样的事情会起作用我相信......

SELECT i.SenderNumber, a.Name, a.Type, i.Message FROM
inbox i
INNER JOIN
(SELECT SpvName as Name, 'contact' as Type, Number FROM contact
 UNION
 SELECT SpvName as Name, 'sub district' as Type, Number FROM sub_district
 UNION
 SELECT SpvName as Name, 'district' as Type, Number FROM district
 UNION
 SELECT SpvName as Name, 'village' as Type, Number FROM village
 ) a
ON i.SenderNumber = a.Number