以下查询对我来说绝对正常:
SELECT * From Customers WHERE Customers.ContactName = (SELECT FirstName FROM Employees as E, orders as O WHERE <condition> LIMIT 1);
但是,如果我使用LIKE而不是=与子查询的结果进行比较,则不会得到任何结果。如何LIKE '%%'在上述查询中使用?
LIKE
=
LIKE '%%'
首先,这个查询 应该 不会是工作的罚款:
SELECT * From Customers WHERE Customers.ContactName = (SELECT FirstName from Employees as E, orders as O WHERE LIMIT 1);
因为WHERE LIMIT 1不正确的SQL。并且,您应该学习使用正确的join语法。大概,您打算:
WHERE LIMIT 1
join
SELECT c.* From Customers c WHERE c.ContactName = (SELECT FirstName FROM Employees as E JOIN Orders as O ON . . . LIMIT 1 );
可以想象,您可以在子查询中添加LIKE代替=和’%’的内容:
WHERE c.ContactName LIKE (SELECT CONCAT('%', FirstName, '%') . . .
但我会这样写EXISTS:
EXISTS
SELECT c.* From Customers c WHERE EXISTS (SELECT 1 FROM Employees as E JOIN Orders as O ON . . . WHERE c.ContactName LIKE CONCAT('%', FirstName, '%') );
这与查询没有完全相同的作用。它做一些更合理的事情。它会确定子查询中是否有 任何 匹配项,而不是比较子查询中的一个随机名称。对于查询来说,这似乎是一个更合理的意图。