MySQL 一列上的 SQL 连接 LIKE 另一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14696793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Join on a column LIKE another column
提问by Don P
Possible Duplicate:
mysql join query using like?
可能的重复:
mysql join 查询使用 like?
I want to do a join where one column contains a string from another table's column:
我想做一个连接,其中一列包含另一个表列中的字符串:
SELECT
a.first_name,
b.age
FROM names a
JOIN ages b
ON b.full_name LIKE '%a.first_name%'
Is this possible? I'm using MySQL. Of course the above query will not work since the LIKE '%a.first_name%' will just look for the string a.first_name, and not the column's actual value.
这可能吗?我正在使用 MySQL。当然,上面的查询将不起作用,因为 LIKE '%a.first_name%' 将只查找字符串 a.first_name,而不是列的实际值。
回答by colin-higgins
You only need to concatenate the strings, you could also do a search and replace.
您只需要连接字符串,您也可以进行搜索和替换。
SELECT
a.first_name,
b.age
FROM names a
JOIN ages b
ON b.full_name LIKE '%' + a.first_name + '%'
回答by fthiella
You can use CONCAT:
您可以使用 CONCAT:
SELECT
a.first_name,
b.age
FROM
names a JOIN ages b
ON b.full_name LIKE CONCAT('%', a.first_name, '%')
or also LOCATE, that returns the position of the first occurrence of a.first_name
in b.full_name
:
或者还有LOCATE,它返回第一次出现a.first_name
in的位置b.full_name
:
SELECT
a.first_name,
b.age
FROM
names a JOIN ages b
ON LOCATE(a.first_name, b.full_name)
if there's a match, the join will succeed.
如果有匹配项,则连接将成功。