使用 HAVING 还是 WHERE?

Use HAVING or WHERE?

我对何时使用 HAVING 以及何时使用 WHERE 感到困惑。我需要

Find all of the bugs on software Debugger that pertain to the /main.html

这是我的查询

select Tickets.TicketID, b.Data
from Bugs b
Inner Join Tickets
On b.TicketID = Tickets.TicketID
Inner Join Softwares
on Software.SoftwareId = Tickets.SoftwareID
where Software.URL = 'http://debugger.com' and Tickets.Title = '/main.html'

注意:这给了我想要的结果 但我想确保我没有遗漏任何重要信息。也许我应该在这里的某个地方使用 HAVING?

另外为了让查询在大型数据集上表现更好,我在外键上创建了一个索引

create nonclustered index IX_Tickets_SoftwareId
on [dbo].[Tickets] ([SoftwareId])
go
create nonclustered index IX_Bugs_TicketsId
on [dbo].[Bugs] ([TicketsId])

还好吗?

您的查询没问题。您想要过滤单个记录,这就是 WHERE 子句的作用。

HAVING 子句在聚合查询中发挥作用 - 使用 GROUP BY 的查询,其目的是使用聚合过滤 组记录 函数(例如 SUM()MAX() 等)。这对您的查询没有意义,因为它不使用聚合。

顺便说一句,我注意到您没有从 softwares table 返回任何内容,因此连接仅用于过滤。在这种情况下,我发现 exists 更合适,因为它的目的很明确:

select t.ticketid, b.data
from bugs b
inner join tickets t on b.ticketid = t.ticketid
where t.title = '/main.html' and exists (
    select 1 
    from softwares s
    where s.softwareid = t.softwareid and s.url = 'http://debugger.com'
)

为了性能,考虑在 softwares(softwareid, url) 上建立索引,以便子查询高效执行。 tickets(ticketid, title) 上的索引也可能有帮助。

WHERE 用于在进行任何分组之前过滤记录。 HAVING用于分组后过滤值。 HAVING 子句的

中只能包含组中的列或表达式