如何在mysql中将同一个表中的三个字段相加

时间:2011-08-19 04:27:36

标签: sql union sum

我有一个包含字段的表,我想从三个不同的字段中总结数据,如下所示。我做了如下代码,但有错误。所以请帮我为我做正确的代码:

    <?php include "config.php"; ?> 
    <?php $results = mysql_query
("SELECT sum(hit),as total from ( 
select hit from sound union 
select hit from soundK union 
select hit from soundD ") ; 
while ( $row = mysql_fetch_array($results) ) 
{ ?> 
<?php echo $row[total];?> <?php }?> 

所以请尽快帮助

提前致谢

2 个答案:

答案 0 :(得分:1)

您有一个额外的,,错过了结束)和派生的表别名:

<?php include "config.php"; ?> 
<?php $results = mysql_query(
    "SELECT sum(hit) as total 
    FROM ( 
        SELECT sum(hit) hit from sound 
        UNION ALL SELECT sum(hit) hit from soundK 
        UNION ALL SELECT sum(hit) hit from soundD 
    ) rs") ; 
while ( $row = mysql_fetch_array($results) ) { ?> 
    <?php echo $row['total'];?>
<?php }?> 

如果您想要3个单独的列:

<?php include "config.php"; ?> 
<?php $results = mysql_query(
    "SELECT soundHits, soundKHits, soundDHits
    FROM ( 
        SELECT sum(hit) soundHits from sound
    ) a, (
        SELECT sum(hit) soundKHits from soundK
    ) b, ( 
        SELECT sum(hit) soundDHits from soundD 
    ) c") ; 
while ( $row = mysql_fetch_array($results) ) { ?> 
    soundHits: <?php echo $row['soundHits'] ;?>
    soundKHits: <?php echo $row['soundKHits'] ;?>
    soundDHits: <?php echo $row['soundDHits'] ;?>
<?php }?> 

答案 1 :(得分:0)

或......

select (
    (select sum(hit) from sound) +
    (select sum(hit) from soundK) +
    (select sum(hit) from soundD))