2012-07-27 16 views
1

我有一個表格,具有以下結構,我想要獲得某個特定的album_id & disc的所有時間的總和。我發現這個http://board.phpbuilder.com/showthread.php?10326769-RESOLVED-time-help,它看上去有點好(在第一個答案代碼的第一個片段),但我找不出如何去解決它第i個MySQL的從php的時間字段中添加多次php

表結構:

CREATE TABLE IF NOT EXISTS `tracks` (
    `id` int(255) NOT NULL AUTO_INCREMENT, 
    `artist_id` int(255) NOT NULL, 
    `album_id` int(255) NOT NULL, 
    `disc` int(3) NOT NULL, 
    `track_no` int(3) NOT NULL, 
    `title` varchar(255) NOT NULL, 
    `length` time NOT NULL, 
    `size` decimal(20,1) NOT NULL, 
    `plays` int(255) NOT NULL, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `artist_id` (`artist_id`,`album_id`,`disc`,`track_no`,`title`) 
) ; 

任何非常感謝幫助。我是一個新手!

+1

我不明白,你想要什麼總結? – 2012-07-27 04:11:54

+0

長度字段來回某個相冊+光盤。 – rackemup420 2012-07-27 04:14:57

回答

2

也許這樣做。

SELECT album_id, disc, SEC_TO_TIME(SUM(TIME_TO_SEC(length))) AS formatTime 
FROM tracks 
GROUP BY album_id, disc 
HAVING album_id=id AND disc=disc 

替代只有特定的圖冊和光盤:

SELECT album_id, disc, SEC_TO_TIME(SUM(TIME_TO_SEC(length))) AS formatTime 
FROM tracks 
WHERE album_id=id AND disc=disc 
+0

我已經在mysql中使用SUM方法嘗試過它,它不wrk,它返回968.但那不是一次。 – rackemup420 2012-07-27 04:24:03

+0

我很確定這是一次。如何嘗試將其轉換爲其他單位? – 2012-07-27 04:26:11

+0

對不起,我的意思是它沒有格式化正確。應該是10:08。 – rackemup420 2012-07-27 04:31:16

0
//this is the album we want 
$album = 24; 

//grab all the track lengths and plays from our album 
$query = ' 
SELECT length, plays 
FROM tracks 
WHERE album_id = "'.$album.'"; 

//do our mysql query 
$result = mysql_query($query) or die(mysql_error()); 

//now for every result do somthing like add the length of the songs or play count 
$length = null; 
$plays = null; 
while ($row = mysql_fetch_assoc($result)) { 
    $length = $length + $row["length"]; 
    $pays = $plays + $row["plays"]; 
} 

//echo data to user 
echo 'The total lenth of this albums is:'.$length.'mins'; 
echo 'this ablum as been played:'.$plays.'times'; 
+0

這對我來說返回0。 – rackemup420 2012-07-27 04:54:09

+0

爲什麼不直接在SQL中做一個'SUM()'!? – Jakub 2012-07-27 05:26:45