如何在MySQL中设置数字通配符?

问题描述 投票:0回答:1

我正在尝试创建一个 SQL 脚本来查找两个不同数据库中的代码。我想设置一个带有数字通配符的参数。

代码通常这样写,例如,

ABC108
ABC109
DEF47213
等。我将参数设置为
ABC[0-9]+
以返回以 ABC 开头的代码的所有可能变体,但这导致了空白输出。

我尝试了以下操作,期望输出两个数据库中最新的代码:

SET @investment_code = 'ABC[0-9]+';

SELECT 
    investment_name, 
    i.service_client_id, 
    currency_symbol, 
    investment_code C_investment_codes
FROM client.investments i
LEFT JOIN client.currencies c
    ON i.currency_id = c.id
WHERE i.investment_code COLLATE utf8mb4_unicode_ci LIKE @investment_code
ORDER BY investment_code DESC
LIMIT 1;

SELECT 
`key`, 
service_client_id, 
`value` SD_investment_codes
FROM client_data.standing_data sd
WHERE sd.`value` COLLATE utf8mb4_unicode_ci LIKE @investment_code
ORDER BY `value` DESC
LIMIT 1;

这导致了空白输出。当我使用

SET @investment_code = 'ABC%';
时,我得到了结果,但我特别想将数字参数设置为遵循 ABC。这是我的预期输出:

C_投资代码 SD_投资代码
ABC109 ABC109
sql mysql parameters wildcard
1个回答
0
投票

在MySQL中,LIKE运算符不直接支持正则表达式。相反,您可以使用 % 通配符来匹配任何字符序列。

对于您的脚本,您可以利用 MySQL 中提供的 REGEXP 运算符,它允许您使用正则表达式。这是一个例子

SET @investment_code = '^ABC[0-9]+$';

SELECT 
    investment_name, 
    i.service_client_id, 
    currency_symbol, 
    investment_code AS C_investment_codes
FROM client.investments i
LEFT JOIN client.currencies c
    ON i.currency_id = c.id
WHERE i.investment_code REGEXP @investment_code
ORDER BY investment_code DESC
LIMIT 1;

table
SELECT 
    `key`, 
    service_client_id, 
    `value` AS SD_investment_codes
FROM client_data.standing_data sd
WHERE sd.`value` REGEXP @investment_code
ORDER BY `value` DESC
LIMIT 1;
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.