我需要查询这个数据库以获取每行数据,但也需要结果中一列数值的总和。我可以使用PHP获取总值,但然后我需要运行两个循环,一个用于获取总值(放置在结果上方的顶部)。所以我更喜欢查询来捕捉它并只创建一个“总计”行,但我使用的唯一方法是具有原始查询的重复子查询。是否有更好的方法?
SELECT
CONCAT(u.firstname, , u.lastname ) name, u.id, s.description, s.shiftstart, s.shiftend,
(SELECT
SUM( TIME_TO_SEC( TIMEDIFF( shiftend, shiftstart ) ) ) /3600
FROM shifts
WHERE id = $user
AND DATE( shiftstart )
BETWEEN $start
AND $end ) total
FROM shifts s
INNER JOIN users u ON ( s.id = u.id )
WHERE s.id = $user
AND DATE( shiftstart )
BETWEEN $start
AND $end
ORDER BY shiftstart
以上工作并输出:
name id description shiftstart shiftend total
Joe User joeuser Stuff 2009-01-05 07:45:00 2009-01-05 12:15:00 39.5000
Joe User joeuser Stuff 2009-01-05 13:00:00 2009-01-05 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-06 07:45:00 2009-01-06 10:45:00 39.5000
Joe User joeuser Stuff 2009-01-06 10:45:00 2009-01-06 12:45:00 39.5000
Joe User joeuser Stuff 2009-01-06 13:30:00 2009-01-06 14:30:00 39.5000
Joe User joeuser Stuff 2009-01-06 14:30:00 2009-01-06 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-07 09:45:00 2009-01-07 14:00:00 39.5000
Joe User joeuser Stuff 2009-01-07 15:00:00 2009-01-07 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-08 08:00:00 2009-01-08 12:15:00 39.5000
Joe User joeuser Stuff 2009-01-08 13:15:00 2009-01-08 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-09 07:45:00 2009-01-09 10:45:00 39.5000
Joe User joeuser Stuff 2009-01-09 11:45:00 2009-01-09 15:15:00 39.5000
Joe User joeuser Stuff 2009-01-09 15:15:00 2009-01-09 17:00:00 39.5000
这就是我需要的,但可能不是最佳的获取方式。