1

这些查询单独工作。如何将 UNION 写入 SUM 所有结果?

SELECT SUM(players) FROM `tournament_players` FROM (
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p1_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
UNION
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p2_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
UNION
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p3_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
UNION
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p4_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
)
4

2 回答 2

5

您走在正确的轨道上,但有一个额外的FROM关键字。尝试这个:

SELECT SUM(players) FROM (
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p1_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
UNION
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p2_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
UNION
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p3_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
UNION
SELECT COUNT(*) as `players` FROM `tournament_players` WHERE `foursome_1_p4_name` IS NOT NULL AND `tournament` BETWEEN 13 AND 17 AND flight = '8 AM'
) `tournament players`
于 2012-10-10T16:29:20.210 回答
1

听起来您只是想要这个,将您的个人查询放在子查询中以获得sum()

SELECT SUM(players) 
FROM 
(
    SELECT COUNT(*) as `players` 
    FROM `tournament_players` 
    WHERE `foursome_1_p1_name` IS NOT NULL 
        AND `tournament` BETWEEN 13 AND 17 
        AND flight = '8 AM'
    UNION
    SELECT COUNT(*) as `players` 
    FROM `tournament_players` 
    WHERE `foursome_1_p2_name` IS NOT NULL 
        AND `tournament` BETWEEN 13 AND 17 
        AND flight = '8 AM'
    UNION
    SELECT COUNT(*) as `players` 
    FROM `tournament_players` 
    WHERE `foursome_1_p3_name` IS NOT NULL 
        AND `tournament` BETWEEN 13 AND 17 
        AND flight = '8 AM'
    UNION
    SELECT COUNT(*) as `players` 
    FROM `tournament_players` 
    WHERE `foursome_1_p4_name` IS NOT NULL 
        AND `tournament` BETWEEN 13 AND 17 
        AND flight = '8 AM'
) x -- place your alias here
于 2012-10-10T16:27:41.473 回答