[英]SELECT in the WHERE LIKE clause
I have the following SQL query:我有以下 SQL 查询:
SELECT * FROM `test2`
WHERE text LIKE (SELECT concat(startswith,"%") from test1 ORDER BY RAND() LIMIT 1)
Essentially I want to pick one row from the test1 table, and then find all the records from the test2 table that start with the characters from the startswith column in test1.本质上,我想从 test1 表中选择一行,然后从 test2 表中找到所有以 test1 中的startswith列中的字符开头的记录。
But this query doesn't do that.但是这个查询并没有这样做。 Where am I going wrong?
我哪里错了?
Here the tables in questing这里是查询表
SELECT * FROM `test1`
startswith
==========
aaa
bbb
ccc
SELECT * FROM `test2`
text
====
aaa3k123k12312p03edwqeq
aaa12313fwefrwerw
aaafwre3we4232
bbb123123rwqe12e1
Move the subquery, and JOIN
:移动子查询和
JOIN
:
SELECT text
FROM `test2`
JOIN (select startswith from test1 ORDER BY RAND() LIMIT 1) t1
ON text LIKE concat(startswith,"%")
像这样在连接中使用子选择
select t2.* from test2 as t2 join (SELECT RAND() as rand, startswith from test1 ORDER BY rand LIMIT 1) as t1 where t2.txt like CONCAT(t1.startswith,"%");
The reason your code doesn't give you the results you expect (for example, with your sample data sometimes it returns values starting with both aaa
and bbb
, or you may not get all the values starting with aaa
) is that the WHERE
condition is evaluated for each row of test2.您的代码没有给您预期的结果的原因(例如,对于您的示例数据,有时它返回以
aaa
和bbb
开头的值,或者您可能无法获得以aaa
开头的所有值)是WHERE
条件是对 test2 的每一行进行评估。 That means that for each row in test2, a new, random value is compared against, this can lead (potentially) to matching all lines, or none, even if all values in test1
are the start of a value in test2
.这意味着对于 test2 中的每一行,都会与一个新的随机值进行比较,这可能导致(可能)匹配所有行,或者不匹配,即使
test1
中的所有值都是test2
值的开始。
The way around this is to create a derived table from your subquery - so that it only gets evaluated once - and then JOIN
that to test2
using the LIKE
comparison you are using:解决这个问题的方法是从您的子查询创建一个派生表 - 这样它只会被评估一次- 然后使用您正在使用的
LIKE
比较将其JOIN
到test2
中:
SELECT t2.*
FROM (SELECT startswith FROM test1 ORDER BY RAND() LIMIT 1) t1
JOIN test2 t2 ON t2.text LIKE CONCAT(t1.startswith, '%')
Demo on dbfiddle dbfiddle 上的演示
Note that if startswith
is "ccc", you will get no results in the output for your sample data.请注意,如果
startswith
是“ccc”,则示例数据的输出中将不会得到任何结果。
Your code seems to be like this SELECT * FROM test2WHERE text LIKE ==========%
without quotations.您的代码似乎是这样的
SELECT * FROM test2WHERE text LIKE ==========%
没有引号。 If you put a temporary data on your query would it still get the results?如果在查询中放置临时数据,它还会得到结果吗? Something like
就像是
SELECT * FROM `test2`
WHERE text LIKE aaa% -->> will not run, should have quotations
and this和这个
SELECT * FROM `test2`
WHERE text LIKE 'aaa%'
To complete your code完成你的代码
SELECT * FROM `test2`
WHERE text LIKE Concat((SELECT startswith from test1 ORDER BY RAND() LIMIT 1), "%")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.