ID值多的总和

时间:2013-06-01 03:53:02

标签: php mysql sql

我尝试获取内容ID,这里是查询...

$getIDs = mysql_query("SELECT content_id FROM playlist_content WHERE playlist_id=".$rrow['playlist_id']."") or die(mysql_error());
    while($row = mysql_fetch_array($getIDs)) { 
        $array[] = $row;
}

这是结果

Array
(
    [0] => Array
        (
            [0] => 33
            [content_id] => 33
        )

    [1] => Array
        (
            [0] => 13
            [content_id] => 13
        )

    [2] => Array
        (
            [0] => 8
            [content_id] => 8
        )
)

现在从第二个表中获取此ID必须获取值 注意:ID = content_id

$result =  mysql_query("SELECT SUM( length ) as total FROM content WHERE ID ...

并且所有行的回声总和['length'在哪里是这个ID 需要支持 102 256 等结果......

或者有更好的方法来获得总和?

2 个答案:

答案 0 :(得分:1)

您可以通过连接两个表

在单个查询中实际执行此操作
SELECT  a.content_id, SUM(b.length) TotalSum
FROM    playlist_content a
        INNER JOIN content b
            ON a.content_id = b.ID 
WHERE   a.playlist_id = IDHERE
GROUP   BY a.content_id

查询结果将为每个length提供content_id的总和。

要进一步了解联接,请访问以下链接:

答案 1 :(得分:1)

试试这个:

$query = "SELECT content_id, " .
" ( select sum (length) from content where id = content_id) as content_length " .
" FROM playlist_content " .
" WHERE playlist_id=".$rrow['playlist_id'];

$getIDs = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($getIDs)) { 
    $array[] = $row;
}