mysql - 连接字符串修改(替换、连接、修剪)

标签 mysql join wildcard sql-like trim

我无法让加入工作。我有额外的空格和尾随内容,所以我想 replacetrimlikeconcat (对于通配符)会起作用,但事实并非如此。

这里是示例数据:

create table table1 (name varchar(200));
create table table2 (name varchar(200));
insert into table1 values
('A test: A Value'),
('A test: Another value');
insert into table2 values
('A Value: extra content'),
('Another Value: More content');

我预计 table1 的第 1 行与 table2 的第 1 行匹配,第 2 行也相同。这些应该匹配,因为表 1 中 A test: 之后的内容与表 2 的前导文本匹配.

我的尝试是:

select *
from table1 as t1
join table2 as t2
on trim(replace(replace(t1.name, 'A test:', ''), '  ', ' ')) 
like concat(trim(replace(t2.name, '  ', ' ')), '%') 

这不会返回任何匹配项,

http://sqlfiddle.com/#!9/940742/4

最佳答案

它不起作用的原因是您尝试加入的条件是第一部分短于第二部分,例如:

关于“A Value”,例如“A Value:额外内容%”

因此,为了使其正常工作,您需要切换参数以使条件变为:

关于“A Value:额外内容”,例如“A Value%”

我认为您应该更改 join 子句,以便 % 与 t1.name 连接,而不是 t2.name。

这应该有效:

select * 
from table1 as t1 
join table2 as t2
on trim(replace(t2.name, '  ', ' ')) 
like concat(trim(replace(replace(t1.name, 'A test:', ''), '  ', ' ')), '%') ;

参见http://sqlfiddle.com/#!9/940742/23

关于mysql - 连接字符串修改(替换、连接、修剪),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271353/

相关文章:

mysql - 计算列上的内连接

wildcard - Google Big Query 在表名中间使用通配符

javascript - Sailsjs从两个不同的mysql数据库获取数据

mysql - 在 where_in 中使用 implode 函数的 Codeigniter 查询生成器

mysql - 多次使用 LEFT JOIN 只带来 1 行

java - 无法加入@JoinColumn(即@Id)

php - 如何以最有效的方式使用通配符?

php - 简化mysql过滤查询

php - 如何在 Laravel 中链接数据库关系(多个 has_many?)

mysql - 在表正则表达式中查找行 - mysql