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

问题描述 投票:0回答:2

我有这个SQL查询返回4列45行。

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行?

mysql sql union union-all
2个回答
2
投票

使用%声明您的变量。

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

或者更新您的查询以添加%

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

2
投票

简单:

ProblemCrossStreet Like 'PARK MANOR'

ProblemCrossStreet Like '%PARK MANOR%'

做不同的事情。第一个寻找精确(ish)匹配。第二个在名称中的任何位置查找模式。

至于第三个查询,它使用的是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, '%');
© www.soinside.com 2019 - 2024. All rights reserved.