MySQL 中的多个字符串文字
Multiple string literals in MySQL
不小心遇到了奇怪的东西
SELECT * from tablename WHERE mytext LIKE '%string1%' '%1234%';
绝对等于
SELECT * from tablename WHERE mytext LIKE '%string1%' AND mytext LIKE '%1234%';
我的代码有问题,或者我不知道它并且在文档中找不到它?
字符串文字会自动连接,如 here 所述。
例如,'hello' 'world'
等同于单个文字 'helloworld'
因此,当你写:
SELECT * from tablename WHERE mytext LIKE '%string1%' '%1234%';
...实际上相当于写:
SELECT * from tablename WHERE mytext LIKE '%string1%%1234%';
如您所述,这有点类似于:
SELECT * from tablename WHERE mytext LIKE '%string1%' AND mytext LIKE '%1234%';
...但不完全是。实际上,前者会匹配 'string1 1234'
但 不会 '1234 string1'
.
尝试以下示例来验证这一点:
create table tablename(
pkey bigint,
mytext varchar(64)
);
insert into tablename values (1, 'a b'), (2, 'a c'), (3, 'b a');
select * from tablename where mytext like '%a%' '%b%'; -- returns 1 row
select * from tablename where mytext like '%a%' and mytext like '%b%'; -- returns two rows
不小心遇到了奇怪的东西
SELECT * from tablename WHERE mytext LIKE '%string1%' '%1234%';
绝对等于
SELECT * from tablename WHERE mytext LIKE '%string1%' AND mytext LIKE '%1234%';
我的代码有问题,或者我不知道它并且在文档中找不到它?
字符串文字会自动连接,如 here 所述。
例如,'hello' 'world'
等同于单个文字 'helloworld'
因此,当你写:
SELECT * from tablename WHERE mytext LIKE '%string1%' '%1234%';
...实际上相当于写:
SELECT * from tablename WHERE mytext LIKE '%string1%%1234%';
如您所述,这有点类似于:
SELECT * from tablename WHERE mytext LIKE '%string1%' AND mytext LIKE '%1234%';
...但不完全是。实际上,前者会匹配 'string1 1234'
但 不会 '1234 string1'
.
尝试以下示例来验证这一点:
create table tablename(
pkey bigint,
mytext varchar(64)
);
insert into tablename values (1, 'a b'), (2, 'a c'), (3, 'b a');
select * from tablename where mytext like '%a%' '%b%'; -- returns 1 row
select * from tablename where mytext like '%a%' and mytext like '%b%'; -- returns two rows