内部联接基于特定条件

时间:2018-01-15 21:46:50

标签: mysql sql

表格如下:

Tb_RefCity (两列varchars)

for col in df:
  if col[:4] =='abc_':
     df[col] = df[col].astype(int) 

Tb_RawData (两列varchars)

RealCity    |   RefCity
------------------------
London        00 Perfor-Lon
Amsterdam     Ort Amster

我希望内联合Tb_RawData与Counter | FakeCity ------------------------ 222234 | 00 Perfor-Lon (2342) 342344 | 00 Perfor-Lon(23L) 534534 | 00 Perfor-Lon (342211 234444 | Ort Amster(761) 234234 | Ort Amster L1) 一起将Tb_RefCity插入RealCity列,并将值反映为City

结果应如下所示(示例)

Tb_FinalTable (Counter = int / City = varchar)

Tb_FinalTable

我当前的查询:

Counter     |   City
-----------------------
222234      |   London
342344      |   London
534534      |   London
234444      |   Amsterdam
234234      |   Amsterdam

问题:

问题出在INSERT INTO Tb_FinalTable SELECT Raw.Counter, Ref.RealCity FROM Tb_RawData As Raw INNER JOIN Tb_RefCity As Ref ON Raw.FakeCity = Ref.RefCity Tb_RawData可能有不同的结尾字符串,但是特定城市的起点始终相同,例如:

FakeCity

我希望我的查询在00 Perfor-Lon Ort Amster 和内连接中结束字符串是独立的,以检查起始字符串与Ref表比较以获得真实城市。希望你明白我的意思。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT Raw.Counter, Ref.RealCity FROM Tb_RawData As Raw INNER JOIN Tb_RefCity 
As Ref ON Raw.FakeCity LIKE CONCAT(Ref.RefCity, '%')

答案 1 :(得分:1)

http://sqlfiddle.com/#!9/cae0da/1

INSERT INTO Tb_FinalTable
SELECT Raw.Counter, Ref.RealCity 
FROM Tb_RawData As Raw 
INNER JOIN Tb_RefCity As Ref 
ON Raw.FakeCity LIKE CONCAT(Ref.RefCity,"%");