我正在尝试构建一个SQL查询,该查询应该吐出所有用户活动,而不是总结或任何事情,只是执行每个活动的完整列表。
我遇到的问题是,我似乎无法让GROUP BY工作,以便打印出每个用户的活动。
SQLFiddle = http://sqlfiddle.com/#!2/5dce6/2
最终,我将构建此JSON对象:
users: [{
userid: '1',
name: 'John',
activities: [{
activity_typeid: 6431,
time: "2013-01-01 00:00:00",
activity_weight: 20
}, {
activity_typeid: 6431,
time: "2013-01-01 00:00:00",
activity_weight: 20
}]
}, {
userid: '2',
name: Peter',
activities: [{
activity_typeid: 6431,
time: "2013-01-01 00:00:00",
activity_weight: 20
}
}]
}]
SQL:
SELECT activity_typeid, userid, time, activity_weight, activityname
FROM activity_entries
WHERE competitionid = '52a99783c5d6f'
答案 0 :(得分:0)
SELECT activity_typeid, userid, time, activity_weight, activityname
FROM activity_entries
WHERE competitionid = '52a99783c5d6f' AND userid = someuserid
答案 1 :(得分:0)
我认为在这种情况下你不需要GROUP BY
。 ORDER BY
仍然有意义。例如:
SELECT activity_typeid, userid, time, activity_weight, activityname
FROM activity_entries
WHERE competitionid = '52a99783c5d6f'
ORDER BY userid
然后你可以遍历查询结果。如果当前数据与先前数据的userid
不同,请创建新的user
对象,否则只需将新activity
添加到现有user
对象的activities
。
答案 2 :(得分:0)
我认为你想使用group_concat()
:
SELECT userid, username,
group_concat(concat_ws(',', activity_typeid, time, activity_weight) separator '; ') as activities
FROM activity_entries
WHERE competitionid = '52a99783c5d6f'
GROUP BY userid;
这将活动放在一个字符串中,每个字符串用分号分隔。然后用逗号分隔各个组件。