SQL - 多选查询返回无结果

时间:2016-12-19 17:35:03

标签: sql sql-server

我有一个查询,我正在尝试从符合特定条件的表中选择一个行号。

当我期待1个数字

时,当前查询返回0结果
SELECT 
    RowNum 
FROM
    (SELECT 
         ID, Name, RowNum = ROW_NUMBER() OVER (ORDER BY ID) 
     FROM
         tblEncroachmentTypes) AS temp
WHERE
    temp.Name LIKE (SELECT EN_TYPE 
                    FROM LakeEncroachments 
                    WHERE EN_ID = '0526')

我创建了一个临时表来尝试简化它,但它仍然没有返回结果

select RowNum 
from #temp1 
where #temp1.Name like (select EN_TYPE from LakeEncroachments where EN_ID = '0526')

我正在努力提供尽可能多的信息,但不确定我还需要什么。

2 个答案:

答案 0 :(得分:1)

如果您需要使用like,则可能需要添加通配符:

SELECT RowNum 
from (Select ID, Name, RowNum = ROW_NUMBER() over (order by ID) from tblEncroachmentTypes) as temp
where temp.Name Like '%'+(Select EN_TYPE from LakeEncroachments WHERE EN_ID = '0526')+'%'

重新格式化如下:

select RowNum
from (
 select ID
  , name
  , RowNum = row_number() over (
   order by ID
   )
 from tblEncroachmentTypes
 ) as temp
where temp.name like '%' + (
  select EN_TYPE
  from LakeEncroachments
  where EN_ID = '0526'
  ) + '%'

此外,如果您对like的子查询返回多个值,则需要采用不同的方法。

答案 1 :(得分:0)

如果子查询提供多行,请使用此查询

WITH temp as
  (SELECT ID, Name, ROW_NUMBER() OVER (ORDER BY ID) as RowNum
  FROM tblEncroachmentTypes) AS temp
SELECT temp.RowNum 
FROM LakeEncroachments 
INNER JOIN temp ON temp.Name LIKE REPLACE(REPLACE(LakeEncroachments.EN_TYPE, '-', '% '), ' ', '% ') + '%'
WHERE EN_ID = '0526'