如何在类似的键上加入两个表?

时间:2017-09-29 22:09:48

标签: mysql

我试图加入两个数据源,这两个数据源都是关闭子网启动IP的。但是,每个中的起始IP都以不同方式重新编码。我可以使用什么语法基于起始IP连接两个表,没有最后一个字符?

我需要构建一个包含每个表中两个描述列的结果。

谢谢!



table 1:
"Starting IP" "Ending IP"  "Description_1" 
10.16.0.1     10.16.0.254  "REF#12345678"
10.16.1.1     10.16.1.254  "REF#987654321"
10.16.2.1     10.16.2.254  "REF#147258369"

table 2:
"Starting IP" "Ending IP"  "Description_2" 
10.16.0.0     10.16.0.255  "testing by Bill"
10.16.1.0     10.16.1.255  "production by Ann"
10.16.2.0     10.16.2.255  "VoIP by George"

desired query result:
"Starting IP" "Ending IP"  "Description_1" "Description_2"
10.16.0.0     10.16.0.255  "REF#12345678"  "testing by Bill"
10.16.1.0     10.16.1.255  "REF#987654321" "production by Ann"
10.16.2.0     10.16.2.255  "REF#147258369" "VoIP by George"




1 个答案:

答案 0 :(得分:1)

SUBSTRING_INDEX(str, delim, count)会在遇到count delim之前返回字符串,并且可能会为您提供服务。

SELECT table2.*, table1.Description_2
FROM table2
LEFT JOIN table1 ON 
   (substring_index(table2.`Starting IP`,'.',3)
   =substring_index(table1.`Starting IP`,'.',3))
然而,这不会非常有效。将其编码为字符串,但实际的bitstring将开启使用按位AND和类似逻辑函数的可能性,这可能更有效。