获取相关表的TIMESTAMPDIFF的平均值?

时间:2013-10-30 09:29:20

标签: mysql mysql-error-1064

我有两个表featuresresponses,其中每个功能可能有多个响应(或者可能是零响应)。响应表有一个beganended列,其中包含时间戳(至少会有一个开始时间戳,结束时可能为NULL)。

我正在尝试提取features的列表,其中包含各自响应的摘要详细信息(如果有)。我没有在responses表上使用GROUP BY,因为我想要包含没有响应的功能。

这是我正在尝试的SQL,但它报告了TIMESTAMPDIFF子句附近的SQL语法错误。

SELECT f.id, f.name, f.description, is_active, 
  (SELECT COUNT(r.id) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id 
     AND r.result IS NULL) AS nr_s, 

  (SELECT COUNT(r.id) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id) AS nr_r, 

  (SELECT SUM(r.is_D) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id) AS is_D, 

  (SELECT AVG(TIMESTAMPDIFF(SECONDS,r.began,r.ended)) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id) AS duration

FROM features f 
WHERE f.is_deleted IS NULL AND f.id_survey=44
ORDER BY f.id ASC

我做错了什么?

1 个答案:

答案 0 :(得分:0)

SECONDS不是有效的unit。你想要SECOND

SELECT f.id, f.name, f.description, is_active, 
  (SELECT COUNT(r.id) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id 
     AND r.result IS NULL) AS nr_s, 

  (SELECT COUNT(r.id) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id) AS nr_r, 

  (SELECT SUM(r.is_D) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id) AS is_D, 

  (SELECT AVG(TIMESTAMPDIFF(SECOND,r.began,r.ended)) FROM responses r 
   LEFT JOIN participants p ON r.id_participant = p.id 
   WHERE p.is_ignored IS NULL 
     AND r.is_deleted IS NULL 
     AND r.id_feature = f.id) AS duration

FROM features f 
WHERE f.is_deleted IS NULL AND f.id_survey=44
ORDER BY f.id ASC