帮助更好地了解JOINS

时间:2013-04-25 09:27:38

标签: sql sql-server database sql-server-2008

我有三个表从中减去数据,为了获得大部分数据,我有一个非常好的查询,但我无法得到一个特定的行,这就是我需要帮助的地方。

表1:

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

表2:

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

表3:

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

到目前为止,我得到的数据如下,使用下面的SQL语法:

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

我得到的结果似乎是

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

然而,当我像接下来一样进行JOIN时,结果就是搞砸了

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'

但现在我得到的结果如下:

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      |

有关如何获取相应IPAddress和EquipmentID的正确显示名称的任何想法?

如果您需要更多说明,请告诉我。感谢您提前提供任何帮助

3 个答案:

答案 0 :(得分: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'

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

答案 1 :(得分: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

答案 2 :(得分:1)

您正在加入Table2两次并使用错误的ID:

我认为你应该JOIN T3 T1 ,然后加入 T1 T2

喜欢这样:

select * from T3
Join T1 on T3.EquipmentID = T1.EquipmentID
Join T2 on T2.EquipmentTypeID = T1.EquipmentTypeID 
WHERE T3.IPAddress LIKE '%192'