比较 MYSQL 中的两个字符串

Compairing two strings in MYSQL

我有一个从 0 到 2 的 20 个数字的序列,我想将这个字符串与保存在我的数据库中的其他序列进行比较,问题是保存在数据库中的字符串的长度 fluctuates.Also比较需要从头到尾进行。 我想要的示例:

20位数字字符串:

'1,1,2,1,2,1,0,1,2,1,2,1,0,1,2,1,1,1,2,1'

数据库中保存的几个字符串:

1 - '1,1,2,1'

2 - '2,1,2,2,2,2'

3 - '2,1'

4 - '1,1,2,1,2,1'

在这种情况下,查询将 return 13

create table mytable ( s varchar(60) );

insert into mytable values
('1,1,2,1'),
('2,1,2,2,2,2'),
('2,1'),
('1,1,2,1,2,1');


set @x = '1,1,2,1,2,1,0,1,2,1,2,1,0,1,2,1,1,1,2,1';

select s from mytable
where right(@x, length(s)) = s;

输出:

s
1,1,2,1
2,1

Fiddle: https://www.db-fiddle.com/f/r5m2hPbnmUu5VQfYvMVtir/0

您可以在这里使用 LIKE 技巧。例如,要检查第一个字符串 1,1,2,1:

SELECT *
FROM yourTable
WHERE ',1,1,2,1,2,1,0,1,2,1,2,1,0,1,2,1,1,1,2,1,' LIKE '%,1,1,2,1,%';