(字符串)在Mysql中使用join进行LIKE查询

时间:2015-02-19 17:09:09

标签: mysql

我正在尝试使用字符串连接表中的两个不同列,这两个字段在两个不同表的两列之间只是部分通用。

我如何组合这两个表:

假设我有2个表,table1,table2

 ╔════╦══════════════════════════════════╦══════╗
 ║ T1 ║  String1                         ║ snr  ║
 ╠════╬══════════════════════════════════╬══════╣
 ║  1 ║ Jeff Atwood is good but naughty  ║ 5636 ║
 ║  2 ║ Geoff Dalgas is bully and fat    ║  148 ║
 ║  3 ║ Jeff Atwood likes skoda and hate ║      ║
 ║    ║ ferrari                          ║  101 ║
 ║  4 ║ Geoff Dalgas is smart but not    ║      ║
 ║    ║  intelligent                     ║  959 ║
 ╚════╩══════════════════════════════════╩══════╝

 ╔════╦══════════════════════════════════╦══════╗
 ║ T2 ║  String2                         ║ bnr  ║
 ╠════╬══════════════════════════════════╬══════╣
 ║  5 ║ Jeff Atwood is good              ║ 1323 ║
 ║  34║ Geoff Dalgas is bully            ║12148 ║
 ║  73║ Jeff Atwood  likes skoda         ║26101 ║
 ║  64║ Geoff Dalgas is smart but        ║56959 ║
 ╚════╩══════════════════════════════════╩══════╝

这就是我想要实现的目标

结果:

 ╔════╦══════════════════════════════════╦══════╦══════╦══════╗
 ║ T1 ║  String1                         ║ snr  ║bnr   ║T2    ║
 ╠════╬══════════════════════════════════╬══════╬══════╬══════╣
 ║  1 ║ Jeff Atwood is good but naughty  ║ 5636 ║1323  ║5     ║
 ║  2 ║ Geoff Dalgas is bully and fat    ║  148 ║12148 ║34    ║
 ║  3 ║ Jeff Atwood likes skoda and hate ║      ║      ║      ║
 ║    ║ ferrari                          ║  101 ║26101 ║73    ║
 ║  4 ║ Geoff Dalgas is smart but not    ║      ║      ║      ║
 ║    ║  intelligent                     ║  959 ║56959 ║64    ║
 ╚════╩══════════════════════════════════╩══════╩══════╩══════╝

我看到的唯一关系是比较string1和string2(部分相等)

这是我的语法:

SELECT table1.T1, table1.String1, table1.snr, table2.bnr,table2.T2 FROM table1 INNER JOIN table2 WHERE table1.string1 LIKE table2.string2

但我得到任何错误

  

您可能在SQL解析器中发现了一个错误。请仔细检查您的查询,并检查引号是否正确且不匹配。其他可能的失败原因可能是您在带引号的文本区域之外上传二进制文件。您还可以在MySQL命令行界面上尝试查询。下面的MySQL服务器错误输出(如果有的话)也可以帮助您诊断问题。如果您仍然遇到问题或解析器在命令行界面成功的地方失败,请将SQL查询输入减少到导致问题的单个查询,并在下面的CUT部分中提交包含数据块的错误报告:

     

错误:C1 C2 LEN:56 57 770 STR:等......

2 个答案:

答案 0 :(得分:0)

如果LIKE参数中没有任何通配符,它​​只会进行精确的字符串匹配。您需要添加%通配符:

SELECT table1.T1, table1.String1, table1.snr, table2.bnr,table2.T2 
FROM table1 
INNER JOIN table2 ON table1.string1 LIKE CONCAT('%', table2.string2, '%')

答案 1 :(得分:-1)

试试这个:

Select ID, String From (
(SELECT t1, string1  FROM table1)
UNION
(SELECT t2,string2  FROM table2)) order by ID;