在MySQL中的RegExp中使用列

dev*_*per 10 regex mysql sql

我正在使用以下查询regexp:

SELECT a.id, a.company, a.name, b.title, b.description, b.t_id
FROM a, b
WHERE ( b.title
REGEXP "[[:<:]]a.company[[:>:]]" OR b.description
REGEXP "[[:<:]]a.company[[:>:]]" OR b.title
REGEXP "[[:<:]]a.name[[:>:]]"  OR b.description
REGEXP "[[:<:]]a.name[[:>:]]" ) AND a.company !=  '' AND a.name !=  ''
Run Code Online (Sandbox Code Playgroud)

但是,此查询不会给出任何结果,也不会给出任何语法错误.

当我替换a.companya.name使用任何公司名称时,此查询运行正常.为什么此查询不适用于列名?

Eri*_*ric 10

您正在搜索文字字符串a.company,而不是列.试试这个:

SELECT a.id, a.company, a.name, b.title, b.description, b.t_id
FROM a, b
WHERE 
    ( 
        b.title REGEXP concat('[[:<:]]', a.company, '[[:>:]]') 
        OR b.description REGEXP concat('[[:<:]]', a.company, '[[:>:]]') 
        OR b.title REGEXP concat('[[:<:]]', a.name, '[[:>:]]')
        OR b.description REGEXP concat('[[:<:]]', a.name, '[[:>:]]')
    ) 
    AND a.company !=  '' AND a.name !=  ''
Run Code Online (Sandbox Code Playgroud)

这提供了regexp列的值,而不是字符串'a.company'.由于我的猜测是你要比较列值(而不是列名),你需要将它们连接regexp在一起.

您可以使用此查询对此进行测试:

select
    'My col: a.company' as Test1,
    'My col: ' + a.company as Test2
from
    a
Run Code Online (Sandbox Code Playgroud)

在这里,Test1将始终是值My col: a.company,而Test2将是My col: <company col value here>.

  • 您使用的是MS SQL Server字符串连接语法,MySQL不支持.请改用此语法:`CONCAT('[[:<:]]',a.company,'[[:>:]]')` (3认同)