嵌套的SQL查询,它按每个组返回的有限行进行分组

时间:2014-04-05 22:19:03

标签: php mysql sql arrays

尝试获取正确的查询以查看我的表格,如下所示:

id    fromName    toName    messages
1     user1       me        .......
2     user2       me        .......
3     user1       me        .......
4     user1       me        .......
5     user3       me        .......
6     user2       me        .......

我想要做的是获取一个数组,该数组包含来自user1的所有消息,数组中的user2,user3等等。我有一个查询:

$query = mysqli_query($link, "SELECT * FROM messages WHERE toName='$to' OR fromName='$to' order by id desc");
$messages = array();
while ($row = mysqli_fetch_assoc($query)) {
    $messages[$row['fromName']][] = $row;
}

现在我想对它返回的行数进行限制...例如,所有用户限制为2行。我是否需要使用“分组依据”的嵌套查询?此查询无效:

$query = mysqli_query($link, "SELECT * FROM messages WHERE toName='$to' OR fromName='$to' group by fromName order by id desc limit 2");
//or this one
    $query = mysqli_query($link, "SELECT * FROM messages WHERE toName='$to' OR fromName='$to' AND id IN(SELECT * FROM messages group by fromName)");
$messages = array();
while ($row = mysqli_fetch_assoc($query)) {
    $messages[$row['fromName']][] = $row;
}

希望这不是太难解决....提前致谢!

2 个答案:

答案 0 :(得分:1)

为什么不在分配另一个查询之前使用原始查询并对数组运行计数。

if(count($messages[$row['fromName']]) < 2)
    $messages[$row['fromName']][] = $row;
}

答案 1 :(得分:0)

您应该在查询中使用GROUP BY来获得结果。您不需要遍历结果并制定数组。

更新的代码:

$query = mysqli_query($link, "SELECT * FROM messages WHERE toName='$to' OR fromName='$to' GROUP BY fromName");
$senderMessages = mysqli_fetch_assoc($query);