以下查询对我来说绝对正常:
SELECT * From Customers
WHERE Customers.ContactName = (SELECT FirstName
FROM Employees as E, orders as O
WHERE <condition>
LIMIT 1);
但是,如果我使用LIKE
而不是=
来与子查询的结果进行比较,那么我没有得到任何结果。
如何在上述查询中使用LIKE '%%'
?
答案 0 :(得分:2)
首先,此查询应该无法正常工作:
SELECT *
From Customers
WHERE Customers.ContactName = (SELECT FirstName
from Employees as E, orders as O
WHERE LIMIT 1);
因为WHERE LIMIT 1
不是正确的SQL。而且,您应该学会使用正确的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
来写这个:
SELECT c.*
From Customers c
WHERE EXISTS (SELECT 1
FROM Employees as E JOIN
Orders as O
ON . . .
WHERE c.ContactName LIKE CONCAT('%', FirstName, '%')
);
这与您的查询完全不同。它做了更合理的事情。它将确定子查询中是否存在任何匹配,而不是比较子查询中的一个随机名称。对于查询来说,这似乎是一个更合理的意图。
答案 1 :(得分:1)
我想这对你有用,不是吗?
SELECT * From Customers
WHERE Customers.ContactName LIKE '%' + (
SELECT FirstName from Employees as E, orders as O
WHERE <condition>
LIMIT 1
) + '%';
答案 2 :(得分:1)
使用您的方法,您需要使用&#39;%&#39;包装FirstName字段。任意一方将通配符放在您选择的值中。
所以,像
SELECT * From Customers
WHERE Customers.ContactName LIKE (SELECT '%' + FirstName + '%'
from Employees as E
inner join, orders as O on...
WHERE <condition>
LIMIT 1);
对我而言,就像你最好加入你的桌子一样。也许这会更好
SELECT c.*
FROM Customers c
INNER JOIN Employees e on c.ContactName like '%' + e.FirstName + '%'
WHERE <condition>
答案 3 :(得分:1)
以下查询是 MSSQL 语句,而不是LIKE
,我使用 CHARINSDEX
。尝试MySQL中的相关功能(检查INSTR
功能)而不是CHARINDEX
。
SELECT
*
FROM
Customers
WHERE
CHARINDEX(( SELECT TOP 1 FirstName
FROM Employees as E, orders as O
WHERE <condition>
), Customers.ContactName, 1
) > 0;
我不确定,但您可以在MySQL
中尝试以下内容。
SELECT
*
FROM
Customers
WHERE
INSTR(Customers.ContactName,
( SELECT FirstName
FROM Employees as E, orders as O
WHERE <condition>
LIMIT 1)) > 0;
答案 4 :(得分:1)
为什么不使用简单的INNER JOIN
:
SELECT Customers.*
FROM Customers
INNER JOIN Employees ON Customers.ContactName LIKE CONCAT('%', Employees.FirstName,'%')
WHERE Employees.Foo = 'Bar'
注意:+
是加法运算符,不能用于连接字符串。
答案 5 :(得分:0)
SQL Server
这将返回特定关键字
select *
from Customers
where Customers.ContactName like (select top 1 FirstName from Employees )
如果关键字存在,则会返回
select *
from Customers
where Customers.ContactName like '%' + (select top 1 FirstName from Employees) + '%'
答案 6 :(得分:0)
我建议:
SELECT * From Customers as a
INNER JOIN (SELECT '%'+FirstName+'%' as FirstName from Employees as E, orders as O
WHERE <condition>
LIMIT 1) as b
ON a.ContactName LIKE b.Firstname;
答案 7 :(得分:0)
如果您拥有员工表的外键,则无需使用 LIKE 。但是,如果您想使用它,可以尝试以下
select *
from customers a, employees b
where (contions on employees)
and customers.contactname like '%'||b.firstname||'%';