我需要一些mysqli查询的帮助。我有一个表,其中包含用户,卡片,动作等字段......如此
id user card action time
1 1 1 1 5
2 1 1 2 6
3 1 1 3 7
4 2 1 1 8
我需要获得 10个最后用户的数组及其所有操作,例如
array(
2 => array(1),
1 => array(1,2,3)
)
我尝试使用distinct但它只为每个用户返回一个动作,并且对它进行多次查询可能不是最好的解决方案,我想不出其他任何尝试。也许需要合并查询,但我无法弄清楚如何做到这一点。
谢谢!
好吧,使用帮助我自己做了我自己的查询,但由于某种原因,它无法调整最高时间值,其他一切正常。 http://sqlfiddle.com/#!2/68751d/1
$m = new_m();
if ($s = $m -> prepare("SELECT user, group_concat(action) as actions, time FROM cards_actions_data WHERE card=? GROUP BY user ORDER BY time DESC LIMIT 0, 10")) {
$s -> bind_param('i', $card);
$s -> execute();
$s -> bind_result($user,$actions,$time);
while($s -> fetch()){
$users[$user]['time'] = $time;
$users[$user]['actions'] = $actions;
}
$s -> close();
}
pre($users);
pre($m);
$m -> close();
return $users;
答案 0 :(得分:0)
据我了解你可能会寻找GROUP_CONCAT
。试试这个:
SELECT user , group_concat(`action`) actions , max(`time`) `time`
FROM table1
GROUP BY user
ORDER BY `time` DESC
LIMIT 10
答案 1 :(得分:0)
SELECT user, GROUP_CONCAT(action)
FROM my_table NATURAL JOIN (
SELECT DISTINCT user FROM my_table ORDER BY time DESC LIMIT 10
) t
GROUP BY user