考虑以下表格:
drop table if exists testA;
drop table if exists testB;
create table testA ( id int, testX varchar(255) );
create table testB ( id int, testY varchar(255) );
insert into testA values ( 1, 'this is a test%' );
insert into testB values ( 1, 'test%' );
insert into testA values ( 1, 'a test% this is' );
结果如下:
mysql> select * from testA;
+------+-----------------+
| id | testX |
+------+-----------------+
| 1 | this is a test% |
| 1 | a test% this is |
+------+-----------------+
2 rows in set (0.04 sec)
mysql> select * from testB;
+------+-------+
| id | testY |
+------+-------+
| 1 | test% |
+------+-------+
1 row in set (0.05 sec)
如何从testA表中获取以 testB值结束?
的值?此查询:
SELECT tA.testX
FROM testA tA
JOIN testB tB USING (id)
WHERE tA.testX LIKE CONCAT('%', tB.testY);
返回整个结果:
+-----------------+
| testX |
+-----------------+
| this is a test% |
| a test% this is |
+-----------------+
2 rows in set (0.04 sec)
这当然是合乎逻辑的,因为CONCAT('%', tB.testY)
将返回'%test%'。但是在我的应用程序中,我在LIKE的右侧有复杂的值,包含函数调用以及列和字符串的混合。
答案 0 :(得分:1)
我终于找到了解决方案:
SELECT tA.testX
FROM testA tA JOIN testB tB USING (id)
WHERE RIGHT(tA.testX, LENGTH(tB.testY)) = tB.testY
给我:
+-----------------+
| testX |
+-----------------+
| this is a test% |
+-----------------+
你可以用:
LIKE 'xxx%'
)开头的字符串。LIKE '%xxx'
)结尾的字符串LIKE '%xxx%'
)的字符串我发布它以防有人会发现它有用。