1

考虑下表:

 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 的右侧有复杂的值,包含函数调用以及列和字符串的混合。

4

1 回答 1

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% |
+-----------------+

你可以这样做:

  • LEFT如果您需要以值 ( ) 开头的字符串LIKE 'xxx%'
  • 正确,如果您需要搜索以值 ( LIKE '%xxx')结尾的字符串
  • LOCATE如果您需要搜索包含值的字符串 ( LIKE '%xxx%')

我发布它以防有人会发现它有用。

于 2012-10-30T18:05:57.727 回答