我需要将表设置属性 MATCH 更新为 True,其中 attribute_a 以 attribute_b 的值开头。
不知何故,我无法在 Postgresql 中获得正确的语法来进行此模式匹配。
UPDATE table
SET match= True
WHERE attribute_a ~ '^attribute_b' ;
例如 MATCH TRUE:attribute_a = 纳尔逊·曼德拉; attribute_b = '纳尔逊'
最佳答案
您不需要模式匹配,请使用left()
,例如:
with my_table(attribute_a, attribute_b) as (
values
('Nelson Mandela', 'Nelson'),
('Donald Trump', 'Donald Duck'),
('John Major', 'John M')
)
select *
from my_table
where attribute_b = left(attribute_a, length(attribute_b));
attribute_a | attribute_b
----------------+-------------
Nelson Mandela | Nelson
John Major | John M
(2 rows)
如果您绝对想使用正则表达式,则必须使用 concat()
或 format()
构建模式,如下所示:
select *
from my_table
where attribute_a ~ concat('^', attribute_b)
-- where attribute_a ~ format('^%s', attribute_b)
关于匹配的正则表达式以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42861852/