0

I have 3 tables from where I substract data, and to get most of the data I have a query that works pretty good, but I can't get a specific row and that's where I need some help.

Table 1:

EquipmentID  | EquipmentName | EquipmentTypeID
15           | Tesla         | 68
16           | Colombus      | 93

Table 2:

EquipmentTypeID | DisplayName      | 
68              | Electrical Device|
93              | GPS Device       |

Table 3:

EquipmentID  | IPAddress  |
15           | 192.168.1.1|  
16           | 192.168.0.1|

So far the data I get is the following using the folowing SQL Syntax:

SELECT DISTINCT t1.IPAddress,
t2.EquipmentID
FROM Table3 t1
JOIN Table1 t2 ON t1.EquipmentID = t2.EquipmentID
WHERE IPAddress LIKE '%192%'

The result I get looks like

IPAddress  | EquipmentID |
192.168.1.1| 15          |
192.168.0.1| 16          |

However when I do a JOIN like the followiing then the result is just messed up

SELECT DISTINCT t1.IPAddress,
t2.EquipmentID,
t3.EquipmentTypeID,
t4.DisplayName
FROM Table3 t1
JOIN Table1 t2 ON t2.EquipmentID = t1.EquipmentID
JOIN Table2 t3 ON t3.EquipmentTypeID = t1.EquipmentTypeID
JOIN Table2 t4 ON t3.EquipmentTypeID = t1.EquipmentTypeID
WHERE IPAddress LIKE '%192'

But now the result I get is the following:

IPAddress  | EquipmentID |EquipmentTypeID| DisplayName     |
192.168.1.1| 15          |68             | ElectricalDevice|
192.168.1.1| 15          |93             | GPS Device      |
192.168.0.1| 16          |68             | ElectricalDevice|
192.168.0.1| 16          |93             | GPS Device      |

Any ideas on how to get the right display name for the corresponding IPAddress and EquipmentID?

If you need more clarification please let me know. Thank you for any help in advance

4

3 回答 3

1

您两次加入 Table2 并且使用了错误的 ID:

我认为你应该JOIN T3T1然后 JOIN T1T2

像这样 :

select * from T3
Join T1 on T3.EquipmentID = T1.EquipmentID
Join T2 on T2.EquipmentTypeID = T1.EquipmentTypeID 
WHERE T3.IPAddress LIKE '%192'
于 2013-04-25T09:48:47.013 回答
1

您两次加入 Table2 并且使用了错误的 ID:

JOIN Table2 t3 ON t3.EquipmentTypeID = t1.EquipmentTypeID
JOIN Table2 t4 ON t3.EquipmentTypeID = t1.EquipmentTypeID

试试这种方式:

SELECT DISTINCT t3.IPAddress,
t2.EquipmentID,
t3.EquipmentTypeID,
t2.DisplayName
FROM Table3 t3
JOIN Table1 t1 ON t1.EquipmentID = t3.EquipmentID
JOIN Table2 t2 ON t2.EquipmentTypeID = t3.EquipmentTypeID
WHERE IPAddress LIKE '%192'

注意:我更改了连接表的名称,因为它有点令人困惑。

于 2013-04-25T09:42:17.707 回答
1
SELECT 
t3.IPAddress,
t3.EquipmentID,
t2.EquipmentTypeID,
t2.DisplayName
FROM Table3 t3
JOIN Table1 t1 ON t3.EquipmentID = t1.EquipmentID
JOIN Table2 t2 ON t2.EquipmentTypeID = t1.EquipmentTypeID
WHERE IPAddress LIKE '%192.%'
GROUP BY
t3.IPAddress,
t3.EquipmentID,
t2.EquipmentTypeID,
t2.DisplayName
于 2013-04-25T09:42:47.027 回答