为什么这3个查询没有返回正确的记录

jrcvhitl  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(341)

我有一个返回4列45行的sql查询。

Select ComplaintID, ProblemStreet, ProblemCrossStreet,ProblemSubdivision
 From Complaints 
 where ProblemCrossStreet Like '%PARK MANOR%' OR ProblemStreet Like '%PARK 
MANOR%' Or ProblemSubdivision Like '%PARK MANOR%'

此查询返回4列31行:

DECLARE @a as varchar(Max) = 'PARK MANOR'
Select ComplaintID, ProblemStreet, ProblemCrossStreet,ProblemSubdivision
From Complaints 
 where ProblemCrossStreet Like @a OR ProblemStreet Like @a Or 
ProblemSubdivision Like @a

我需要返回这个查询,它应该是2列45行

DECLARE @a as varchar(Max) = 'PARK MANOR'
Select  ComplaintID,ProblemCrossStreet From Complaints Where 
ProblemCrossStreet like @a
Union ALL
Select ComplaintID,ProblemStreet from Complaints Where ProblemStreet Like @a
Union ALL
Select ComplaintID, ProblemSubdivision From Complaints where 
ProblemSubdivision like @a

最后一个查询怎么只返回34行?为什么这3个看起来相同的查询不返回相同的值,最重要的是,如何让我的第三个查询返回这2列和45行?

cqoc49vn

cqoc49vn1#

简单:

ProblemCrossStreet Like 'PARK MANOR'

ProblemCrossStreet Like '%PARK MANOR%'

做不同的事情。第一个寻找一个精确的匹配。第二种方法在名称中的任何地方寻找模式。
至于第三个查询,它使用 union all . 所以,如果一行匹配两个条件,那么表单返回两行。
你到底想要哪一个还不清楚。如果需要通配符匹配,则在 like 图案。如果您希望每个匹配都有一个单独的行,那么使用 union all .
编辑:
你似乎想要:

declare @a as varchar(Max) = 'PARK MANOR';

Select  ComplaintID, ProblemCrossStreet
From Complaints
Where ProblemCrossStreet like concat('%', @a, '%')
Union ALL
Select ComplaintID, ProblemStreet
from Complaints
Where ProblemStreet Like concat('%', @a, '%')
Union ALL
Select ComplaintID, ProblemSubdivision
From Complaints
where ProblemSubdivision like concat('%', @a, '%');
3z6pesqy

3z6pesqy2#

用%来声明变量。

DECLARE @a as varchar(Max) = '%PARK MANOR%'

或更新查询以添加%

where ProblemCrossStreet Like CONCAT('%', @a, '%') OR ProblemStreet Like CONCAT('%', @a, '%') Or 
ProblemSubdivision Like CONCAT('%', @a, '%')

相关问题