左连接选择最后一行和左连接选择某一行作为列

时间:2016-11-17 19:02:08

标签: mysql

首先,我展示了我当前的查询。

SELECT u.id, u.username, GROUP_CONCAT(DISTINCT up.weight) as weights, GROUP_CONCAT(DISTINCT pd.type_change, ':', pd.sum_type_change) as statistics
FROM user u
LEFT JOIN
    (SELECT up.weight, up.user_id FROM user_parameter up WHERE up.date BETWEEN '2015-10-10 00:00:00' AND '2017-10-10 00:00:00' ORDER BY up.user_id, up.date ASC) up
    ON u.id = up.user_id
LEFT JOIN
    (SELECT pd.type_change, count(pd.id) as sum_type_change, dd.user_id FROM diet_day dd
     LEFT JOIN product_day pd ON dd.id = pd.diet_day_id
     WHERE dd.date_start BETWEEN '2015-10-10 00:00:00' AND '2017-10-10 00:00:00' GROUP BY dd.user_id, pd.type_change) pd
    ON u.id = pd.user_id
GROUP BY u.id

这样可以正常工作,但我必须先减去最后一个up.weight而不是

GROUP_CONCAT(DISTINCT up.weight)

除此之外我还要改变

GROUP_CONCAT(DISTINCT pd.type_change, ':', pd.sum_type_change)

这总是返回这样的字符串[1:count,2:count,3:count,4:count] 我需要有四个新列,而不是一列(group_concat)。

可以在mysql查询中完成所有这些吗?

1 个答案:

答案 0 :(得分:1)

您需要单独的子查询才能获得第一个和最后一个up.weight

SELECT u.id, u.username, lastup.weight - firstup.weight as delta_weight, 
       GROUP_CONCAT(DISTINCT pd.type_change, ':', pd.sum_type_change) as statistics
FROM user u
LEFT JOIN
    (SELECT up.weight, up.user_id 
     FROM user_parameter up
     JOIN (SELECT user_id, MAX(up.date) AS maxdate
           FROM user_parameter
           WHERE date BETWEEN '2015-10-10 00:00:00' AND '2017-10-10 00:00:00'
           GROUP BY user_id) AS maxup
     ON up.user_id = maxup.user_id AND up.date = maxup.maxdate
     WHERE up.date BETWEEN '2015-10-10 00:00:00' AND '2017-10-10 00:00:00') lastup
    ON u.id = lastup.user_id
LEFT JOIN
    (SELECT up.weight, up.user_id 
     FROM user_parameter up
     JOIN (SELECT user_id, MIN(up.date) AS mindate
           FROM user_parameter
           WHERE date BETWEEN '2015-10-10 00:00:00' AND '2017-10-10 00:00:00'
           GROUP BY user_id) AS minup
     ON up.user_id = maxup.user_id AND up.date = minup.mindate
     WHERE up.date BETWEEN '2015-10-10 00:00:00' AND '2017-10-10 00:00:00') firstup
    ON u.id = firstup.user_id
LEFT JOIN
    (SELECT pd.type_change, count(pd.id) as sum_type_change, dd.user_id 
     FROM diet_day dd
     LEFT JOIN product_day pd ON dd.id = pd.diet_day_id
     WHERE dd.date_start BETWEEN '2015-10-10 00:00:00' AND '2017-10-10 00:00:00' GROUP BY dd.user_id, pd.type_change) pd
    ON u.id = pd.user_id
GROUP BY u.id

关于在单独的列中获取统计信息而不是将其与GROUP_CONCAT连接起来,请参阅MySQL pivot table