我有两张表projects
和project_hours
,一对多(一个项目,多个小时)。
以下是我的两张表:
CREATE TABLE `projects` (
`project_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`client_id` int(10) unsigned NOT NULL,
`project_name` char(50) NOT NULL,
`project_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`project_id`),
KEY `project_owner` (`client_id`),
CONSTRAINT `projects_ibfk_1` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `project_hours` (
`hours_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`project_id` int(10) unsigned NOT NULL,
`start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`end_time` datetime NOT NULL,
PRIMARY KEY (`hours_id`),
KEY `project_id` (`project_id`),
CONSTRAINT `project_hours_ibfk_1` FOREIGN KEY (`project_id`) REFERENCES `projects` (`project_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我想要做的是选择所有项目,并获得小时数的总和,因此我有一个总小时的项目最终列表。因此,如果我在project_hours中有1个项目,2个记录,我想要返回1行,而不是2行。
这是我尝试过的。我得到的是2行,每个时间跨度不到1小时,因此current_hours显示为0
。我该怎么做才能将两行相加?得到1.50或其他东西?
select *, datediff(start_time, end_time) * 60 as current_hours from projects
left join project_hours using(project_id)
where client_id = 2
答案 0 :(得分:0)
我们走吧!这似乎符合我的要求:
select *, sum(time_to_sec(timediff(end_time, start_time))) / 60 / 60 as current_hours from projects
left join project_hours using(project_id)
where client_id = 2
group by project_id