我可以有效地进行简单的连接,但是我面对以下复杂的SQL语句来加入第3个表以在结果中显示HostName
。
我想添加切换表中存在的列HostName
(SwitchID
是主键,HostName
是列)。
目前的陈述是:
SELECT SwitchID, SUM(score)
我需要通过加入switch表在结果中显示SwitchID, HostName, SUM(score)
。
我尝试了许多变化,但无法使其发挥作用。
SELECT SwitchID
, SUM(score)
FROM ( SELECT SwitchID
, CallStackDepth * COUNT(*) AS score
FROM huntandpagingfeatures
JOIN huntgroupmembers
ON huntgroupmembers.HuntGroupDN = huntandpagingfeatures.ListDN
WHERE IsHuntGroup = 1
GROUP
BY SwitchID
, ListDN
UNION
ALL
SELECT IF( ucw.currentportid IS NOT NULL
, ucw.currentswitchid
, ucw.homeswitchid
)
AS SwitchID
, count(*) / 2 AS score
FROM userprogbuttons AS upb
INNER
JOIN usercurrentswitch AS ucw
ON upb.userdn = ucw.userdn
WHERE upb.functionid = 30
GROUP
BY SwitchID
) AS t
GROUP
BY SwitchID
答案 0 :(得分:0)
SELECT t.SwitchID, SUM(score), s.HostName
FROM ( SELECT SwitchID
, CallStackDepth * COUNT(*) AS score
FROM huntandpagingfeatures
JOIN huntgroupmembers
ON huntgroupmembers.HuntGroupDN = huntandpagingfeatures.ListDN
WHERE IsHuntGroup = 1
GROUP
BY SwitchID
, ListDN
UNION
ALL
SELECT IF( ucw.currentportid IS NOT NULL
, ucw.currentswitchid
, ucw.homeswitchid
)
AS SwitchID
, count(*) / 2 AS score
FROM userprogbuttons AS upb
INNER
JOIN usercurrentswitch AS ucw
ON upb.userdn = ucw.userdn
WHERE upb.functionid = 30
GROUP
BY SwitchID
) AS t
JOIN switches s ON t.SwitchID = s.SwitchID
GROUP BY t.SwitchID, s.HostName
答案 1 :(得分:0)
为简洁省略了子查询:
select
SwitchID,
HostName,
sum(Score)
from
( ... ) as t
join
switches s on t.SwitchID = s.SwitchID
group by
SwitchID,
HostName
只需将HostName添加到group by
并完成。
答案 2 :(得分:0)
您可以按HostName分组以及切换ID:
SELECT SwitchID, SUM(score), HostName
--- skipping most of query for simplicity
) AS t
INNER JOIN Switches ON Switches.SwitchID = t.SwitchID
GROUP BY t.SwitchID, Switches.HostName
您还可以使用列列表中的子选择来返回主机名:
SELECT SwitchID, SUM(score),
(SELECT HostName FROM Switches WHERE Switches.SwitchID = t.SwitchID) AS HostName