【发布时间】:2020-12-03 03:51:24
【问题描述】:
我有两张桌子
人
PersonId | Device1 | Device2 | Device3
---------+---------+---------+--------
1 10 20 30
设备
DeviceId | Name | Description | PicklingCoefficient
---------+------+-------------+--------------------
10 AA Whatever 1
20 BB Who knows -1
30 CC Blah blah 100
还有一个将第一个到第二个连接三次的查询:
select p.PersonId, d1.*, d2.*, d3.* from People p
left join Device d1 on d1.DeviceId = p.Device1
left join Device d2 on d2.DeviceId = p.Device2
left join Device d3 on d3.DeviceId = p.Device3
这会生成格式为(人员 + 设备 + 设备 + 设备)的表头,其中 Device 表字段仅重复 3 次:
PersonId | Device1 | Device2 | Device3 | DeviceId | Name | Description | PicklingCoefficient | DeviceId | Name | Description | PicklingCoefficient | DeviceId | Name | Description | PicklingCoefficient
我可以在技术上构建一个字符串生成器,在我提交查询之前为每个 d(n) 表生成一些唯一名称,但是有没有办法简化它?
可能通过在查询的第一行附加一些内容来给我格式(人+设备1+设备2+设备3):
PersonId | Device1 | Device2 | Device3 | DeviceId1 | Name1 | Description1 | PicklingCoefficient1 | DeviceId2 | Name2 | Description2 | PicklingCoefficient2 | DeviceId3 | Name3 | Description3 | PicklingCoefficient3
我希望这样的事情会起作用:
select p.PersonId, d1.* + '1', d2.* + '2', d3.* + '3' from People p
【问题讨论】:
-
您可以使用别名,将 d1.* 替换为 d1.DeviceId 为 DeviceId1,d1.Name 替换为 Name1 ...
-
这就是我想避免的,必须手动输入所有列名,因为 a) 有很多列 b) 连接数是动态的
-
上述声明不是动态的,@jamheadart。如果是,您应该向我们展示相同的动态语句,因为您很可能能够动态地实现您想要的。但问题是,为什么你的陈述是动态的?
-
此外,您的
People表包含Device1、Device2等列本身就是一个设计缺陷。也许真正的解决方案是规范你的设计。 -
为什么每个设备不一行(使用 UNION)?那么你就没有重复的列名了。
标签: sql sql-server