好的,我的头疼了......!
这个美丽的MySQL查询:
(SELECT mtwitterfollowers AS twitfollow FROM `media` WHERE media.id=1)
UNION
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN positions ON position_id = positions.id WHERE peoplejoin.media_id = 1)
UNION
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN networkjoin ON networkjoin.network_id = peoplejoin.network_id LEFT JOIN positions ON position_id = positions.id WHERE networkjoin.media_id = 1)
...返回三行漂亮的数字。
理想情况下,我希望此查询返回所有三个“twitfollow”结果,一起使用。
然而,对它们进行舍入会给我一个错误,“每个派生表都必须有自己的别名”,而且我对如何解决这个问题感到有些困惑。
(当然,我可以在PHP中总结结果;但我假设使用MySQL服务器更快地完成此操作。我会是对的吗?)
答案 0 :(得分:28)
将整个查询用作另一个查询的FROM
子句:
SELECT SUM(twitfollow) FROM (
(SELECT mtwitterfollowers AS twitfollow FROM `media` WHERE media.id=1)
UNION ALL
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN positions ON position_id = positions.id WHERE peoplejoin.media_id = 1)
UNION ALL
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN networkjoin ON networkjoin.network_id = peoplejoin.network_id LEFT JOIN positions ON position_id = positions.id WHERE networkjoin.media_id = 1)
) t1
我还将您的UNION
更改为UNION ALL
,因为您可能不想删除行只是因为一个表中的总和等于另一个表中的总和。
答案 1 :(得分:0)
只需围绕它包装聚合查询:
SELECT SUM(twitfollow)
FROM
(
(SELECT mtwitterfollowers AS twitfollow FROM `media` WHERE media.id=1)
UNION ALL
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN positions ON position_id = positions.id WHERE peoplejoin.media_id = 1)
UNION ALL
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN networkjoin ON networkjoin.network_id = peoplejoin.network_id LEFT JOIN positions ON position_id = positions.id WHERE networkjoin.media_id = 1)
)
答案 2 :(得分:0)
为什么不缩短它,如下所示?
SELECT SUM(
(SELECT mtwitterfollowers AS twitfollow FROM `media` WHERE media.id=1)
+
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN positions ON position_id = positions.id WHERE peoplejoin.media_id = 1)
+
(SELECT SUM(twitterfollowers) AS twitfollow FROM people LEFT JOIN peoplejoin ON peoplejoin.people_id = people.id LEFT JOIN networkjoin ON networkjoin.network_id = peoplejoin.network_id LEFT JOIN positions ON position_id = positions.id WHERE networkjoin.media_id = 1)
) AS twitterfollowers