像子查询SQL Server中的运算符

时间:2015-07-23 18:25:50

标签: sql-server join sql-like

我有一个嵌入了子查询的查询。我想使用like运算符而不是IN运算符。 IN运算符工作正常,但不能提供我需要的所有结果......

我已尝试过以下查询,但获取:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

查询:

SELECT a.Name, 
  CONVERT(nvarchar(50),RTRIM(b.[num])) + ' - ' + CONVERT(nvarchar(50),b.name) AS 'My Code'
FROM firstTable a 
left join secondTable b ON (a.id = b.id)
WHERE a.Name like (select RTRIM(LTRIM('%' + [Customer_Name] + '%')) FROM thirdTable)

3 个答案:

答案 0 :(得分:0)

您可以使用此查询,但由于这是使用LIKE运算符进行连接,因此性能可能不是很好:

SELECT a.Name, CONVERT(nvarchar(50),RTRIM(b.[num])) + ' - ' + CONVERT(nvarchar(50),b.name) AS 'My Code'
 FROM firstTable a 
     left join secondTable b ON (a.id = b.id)
     INNER JOIN thirdTable c ON a.Name LIKE '%' + c.[Customer_Name] + '%'

答案 1 :(得分:0)

您无法使用in进行部分匹配,但可以在like子句中使用on
试试这个:

SELECT a.Name, 
  CONVERT(nvarchar(50),RTRIM(b.[num])) + ' - ' + CONVERT(nvarchar(50),b.name) AS 'My Code'
FROM firstTable a 
Inner join third table on a.name like rtrim(ltrim('%'+ customer_name +'%'))
left join secondTable b ON (a.id = b.id)

答案 2 :(得分:0)

这将返回多个不满足查询的记录

WHERE a.Name like (select RTRIM(LTRIM('%' + [Customer_Name] + '%')) FROM thirdTable)

而不是你可以使用

SELECT a.Name, CONVERT(nvarchar(50),RTRIM(b.[num])) + ' - ' + CONVERT(nvarchar(50),b.name) AS 'My Code'
 FROM firstTable a 
     left join secondTable b ON (a.id = b.id)
     INNER JOIN thirdTable c ON a.Name LIKE '%' + c.[Customer_Name] + '%'

OR

SELECT a.Name, 
  CONVERT(nvarchar(50),RTRIM(b.[num])) + ' - ' + CONVERT(nvarchar(50),b.name) AS 'My Code'
FROM firstTable a 
left join secondTable b ON (a.id = b.id)
WHERE a.Name like (select RTRIM(LTRIM('%' + c.[Customer_Name] + '%')) FROM thirdTable c where c.id = @id)

OR

SELECT a.Name, 
  CONVERT(nvarchar(50),RTRIM(b.[num])) + ' - ' + CONVERT(nvarchar(50),b.name) AS 'My Code'
FROM firstTable a 
left join secondTable b ON (a.id = b.id)
WHERE a.Name like (select top 1 RTRIM(LTRIM('%' + [Customer_Name] + '%')) FROM thirdTable)