我正在使用coldfusion和SQL server来管理一些曲棍球统计数据。我有一个SQL查询表现不佳,因为我在实际循环中运行另一个查询,我返回结果。我知道这不好,性能也很差。所以我希望有人可以帮我做正确的事。
我的第一个SQL看起来像这样:
SELECT
S.GameID,
S.LeagueID,
S.SeasonID,
S.DatePlayed,
S.TimePlayed,
S.HomeTeamID,
S.VisitorTeamID,
HomeTeam.TeamName AS HomeTeamName,
VisitorTeam.TeamName AS VisitorTeamName
FROM schedules S
JOIN teams AS HomeTeam ON S.HomeTeamID = HomeTeam.TeamID
JOIN teams AS VisitorTeam ON S.VisitorTeamID = VisitorTeam.TeamID
WHERE S.LeagueID = <cfqueryparam value="#application.leagueid#" cfsqltype="cf_sql_integer">
AND S.SeasonID = <cfqueryparam value="#application.seasonid#" cfsqltype="cf_sql_integer">
ORDER BY S.GameID DESC
这种方式运行得非常快,我们对此很好。但是管理员想要显示哪些预定的游戏分配了统计数据。所以我cfoutput查询并在循环中,我运行另一个使用gameid检查gamestats表的查询。
<cfoutput query="qListGames">
*** table stuff here...
<cfquery name="qCheckStats" datasource="#APPICATION.DSN#">
SELECT GameID
FROM dbo.GameStats
WHERE GameID = #qListGames.GameID#
</cfquery>
<cfif IsDefined("qAssigned.RecordCount") AND qAssigned.RecordCount GT "0">
True
<cfelse>
False
</cfif>
</cfoutput>
这当然会导致严重滞后,因为有100多条记录,而且我一遍又一遍地访问数据库。理想情况下,我想运行一个可以收集我需要显示的所有记录的SQL语句,还要检查gamestats表中的相关记录。如果找到了gamestats,我需要显示true或者如果不是,则需要显示false。我不能围绕实现这一目标所需的SQL。
有人可以告诉我吗? 谢谢。
答案 0 :(得分:4)
您只需要一个OUTER JOIN
(通常缩写为LEFT JOIN
或RIGHT JOIN
)到GameStats表。有几种方法可以获取数据;您可以使用列别名选择GameStats.GameID(以避免与Schedules.GameID冲突)并检查它是否为空或在cfoutput
中具有值。或者您可以直接在查询中选择所需的输出,并完全从循环中删除逻辑:
SELECT
S.GameID,
S.LeagueID,
S.SeasonID,
S.DatePlayed,
S.TimePlayed,
S.HomeTeamID,
S.VisitorTeamID,
HomeTeam.TeamName AS HomeTeamName,
VisitorTeam.TeamName AS VisitorTeamName,
CASE WHEN gs.GameID IS NULL THEN 'False' ELSE 'True' END AS HasGameStats
FROM schedules S
INNER JOIN teams AS HomeTeam ON S.HomeTeamID = HomeTeam.TeamID
INNER JOIN teams AS VisitorTeam ON S.VisitorTeamID = VisitorTeam.TeamID
LEFT JOIN GameStats gs ON s.GameID = gs.GameID
WHERE S.LeagueID = <cfqueryparam value="#application.leagueid#" cfsqltype="cf_sql_integer">
AND S.SeasonID = <cfqueryparam value="#application.seasonid#" cfsqltype="cf_sql_integer">
ORDER BY S.GameID DESC