我无法让加入
工作。我有额外的空格和尾随内容,所以我想 replace
、trim
、like
和 concat
(对于通配符)会起作用,但事实并非如此。
这里是示例数据:
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, ' ', ' ')), '%')
这不会返回任何匹配项,
最佳答案
它不起作用的原因是您尝试加入的条件是第一部分短于第二部分,例如:
关于“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:', ''), ' ', ' ')), '%') ;
关于mysql - 连接字符串修改(替换、连接、修剪),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271353/