简体   繁体   English

根据列值有条件地联接到表

[英]Conditional join to a table based on column value

We have the following table which contains deviceId and customerPrefix columns. 我们有下表,其中包含deviceIdcustomerPrefix列。

tblDeviceInfo: 
deviceId       customerPrefix
1             ABC
2             XYZ

Based on the customer prefix we also have device tables, I have listed only 2 below but we have too many of them and the above tblDeviceInfo table can contain many different customerPrefixes, I know this is a bad practice but this is what we have at the moment and we have to work with it for the time being. 根据客户前缀,我们也有设备表,下面只列出了2个,但是我们有太多设备表,并且上面的tblDeviceInfo表可以包含许多不同的customerPrefixes,我知道这是一个不好的做法,但这就是我们在此刻,我们暂时必须与之合作。

tblDeviceABC
deviceId           deviceName
1              NameABC1
2              NameABC2

tblDeviceXYZ
deviceid           deviceName
1             NameXYZ1
2             NameXYZ2

When I am querying the tblDeviceInfo (which can contain quite a few rows) I would like to be able to get the following: 当我查询tblDeviceInfo(可以包含很多行)时,我希望能够获得以下信息:

deviceId, deviceName, customerPrefix
1            NameABC1          ABC
2            NameXYZ1          XYZ

Currently we get everything from the tblDeviceInfo table, start looping (in C# app) and get the device details from the relevant table based on the customer prefix, I was wondering if there is a way of joining to a table based on the column value and get everything back with one sql like this with dynamic sql 当前,我们从tblDeviceInfo表中获取所有内容,开始循环(在C#应用程序中),并基于客户前缀从相关表中获取设备详细信息,我想知道是否有一种方法可以基于列值连接到表,并且使用动态sql像这样用sql来获得一切

    @sql = 'Select deviceId, customerPrefix From tblDeviceInfo i
  INNER JOIN tblDevice' + d.customerPrefix + ' d ON d.deviceId = i.deviceId'

This is not quite right but is there anyway of achieving this with dynamic sql or with any other way? 这不是很正确,但是是否可以通过动态sql或任何其他方式来实现?

Thanks 谢谢

It's not just bad practice, it is awful. 这不仅是不好的做法,还很糟糕。

But, you might be able to solve the query something like this: 但是,您也许可以解决如下查询:

Select deviceId, customerPrefix From tblDeviceInfo i
LEFT OUTER JOIN tblDeviceABC dABC ON dABC.deviceId = i.deviceId
...
LEFT OUTER JOIN tblDeviceXYZ dXYZ ON dXYZ.deviceId = i.deviceId

There will be a lot of null checking on the result, but you should be able to make it in one (expensive) query. 将对结果进行很多空检查,但是您应该能够在一个(昂贵的)查询中进行检查。

You can union all the tblDEVICE in a subquery andjoin it with the infor table, 你可以union所有tblDEVICE在子查询andjoin它与Infor的表,

SELECT  b.*, a.customerPrefix
FROM    tblDeviceInfo a
        INNER JOIN
        (
            SELECT deviceID, deviceName From tblDeviceABC
            UNION
            SELECT deviceID, deviceName From tblDeviceXYZ
        ) b ON a.deviceID = b.deviceID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM