首页 文章

使用查找表值作为列的SQL查询

提问于
浏览
0

我有3个表:Device,Service,DeviceXService

表(设备)具有与设备关联的设备和字段的列表,例如序列号设备名称等 .

DeviceID | Device Name | SerialNumber
1        | iPhone      | 2352532533
2        | iPad        | 2345435435
3        | android     | 2532532656

表(服务)是一个查找表,其中包含可在电子邮件,互联网,短信等设备上使用的服务列表 .

ServiceID  | ServiceName
1          | email
2          | internet
3          | texting

表(DeviceXService)是一个交叉引用表,其中包含将设备链接到服务的记录以及这些设备的状态 .

例如 .

DeviceID    | ServiceID   | Status
--------------------------------------
1(iPhone)   | 1(email)    | requested
2(ipad)     | 2(internet) | Approved
1(iPhone)   | 3(texting)  | Approved
3(android)  | 3(texting)  | approved

What I would like to do is create a query that would return all the devices FROM the Devices table, but also create a column for each type of service that exists FROM the Service table and return the status of each service for each device FROM the DeviceXService cross-reference table as one table.

例:

Device ID | Device Name | Device Serial No | email    |  texting   |  internet
--------------------------------------------------------------------------------
    1     | iphone      | 2352532533       | requested|  approved  |  null
    2     | ipad        | 2345435435       | null     |  null      |  approved
    3     | android     | 2532532656       | null     |  null      |  approved

注意:如果设备在DeviceXService交叉引用表中没有服务记录,则为null

如果我不能很好地解释这一点,我会道歉,但这可能就是为什么我很难找到类似的例子 . 任何帮助将不胜感激!

1 回答

  • 0

    如果 Service 表中的行数是常量且已知,则可以这样执行:

    select
     d.*,
     (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=1) as email,
     (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=2) as texting,
     (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=3) as internet
    from
     device d;
    

    结果如下:

    id |  name   | serial | email | texting | internet 
    ----+---------+--------+-------+---------+----------
      1 | iphone  | 123    | req   | app     | 
      2 | ipad    | 234    |       |         | app
      3 | android | 345    |       |         | app
    (3 rows)
    

    如果您希望它是动态的,您可以根据Service表 in code 中的数据生成此类查询,然后针对数据库运行它 .

    我不喜欢通过sql查询将行转换为列是最好的方法,如果你可以在代码中更简单地做到这一点 .

    Edit:

    您可以查看this questionthis one,它们涉及相同的主题 - 动态SQL .

相关问题