“Like” operator in inner join in SQL

不羁岁月 提交于 2019-11-29 01:50:13

A bit of an odd data model aside, you've turned the tables around in the LIKE part (table1.name should be a part of table2.name, not the other way around), and you need to add the percents to the value, not the name of the field, that means not quoting the name;

SELECT table1.*, table2.z
FROM table1
INNER JOIN table2
  ON table2.name LIKE CONCAT('%', table1.name, '%') 
 AND table1.year = table2.year

An SQLfiddle to test with.

Your query is incorrect, you are saying that the content of the column should be like abcdTable2.Nameefgh. This would be correct:

Select Table1.*, Table2.z
From Table1
Inner join Table2
On Table1.Name like "%" + Table2.Name+ "%" and Table1.Year=Table2.Year

This query will be quite slow for bigger table, but I'm afraid that if you are joining on a name only, the table can't really be bigger as you'll have duplicates quite soon.

try this:

Select Table1.*, Table2.z
From Table1
Inner join Table2
On Table1.Name like Concat('%',Table2.Name,'%') and Table1.Year=Table2.Year

in your query it will search for string containing Table2.Name (it is like constant)

as a suggestion joining on names is very very bad, what if you have 2 person with the same name??! So you need to have a primary and foreign key for this.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!