我正在使用MySQL。我有两张桌子,我附上了两张桌子的图像?当我按计数应用ORDER然后查询从数据库检索结果但没有正确排序时,我不知道我在做什么错?我在堆栈溢出中搜索了一些类似的问题,但我仍面临同样的问题。
我试过这些但没有成功
$sql = "Select * from gr_groups";
$result = $db->select($sql);
for($j = 0; $j < count($result); $j++)
{
$mygrp_id = $result[$j]['id'];
$query = "Select * from gr_group_memberships where group_id =".$mygrp_id." ORDER BY COUNT(receiver_id) DESC";
$exec_query = $db->select($query);
echo $exec_query[0]['group_id'];
}
提前致谢?
答案 0 :(得分:1)
仅
ORDER BY receiver_id DESC
将解决问题。
<强>更新强>
尝试加入他们 -
SELECT * FROM gr_groups g
LEFT JOIN gr_group_memberships gm on gm.group_id = g.id
ORDER BY COUNT(gm.receiver_id) DESC
这将获取具有按计数排序的所有成员资格的组。
答案 1 :(得分:1)
尝试如下;
$query = "Select * from gr_group_memberships where group_id = ".$mygrp_id." ORDER BY receiver_id DESC";
答案 2 :(得分:1)
你可以计算和排序,但这样会更好
SELECT *,count(receiver_id) as total_receivers
FROM gr_group_memberships
WHERE group_id =".$mygrp_id."
GROUP BY receiver_id
ORDER BY receiver_id DESC;
答案 3 :(得分:1)
尝试此查询:
$query = "Select a.* from gr_group_memberships a
join( select receiver_id,count(receiver_id) as count1
from gr_group_memberships group by receiver_id) b on
a.receiver_id=b.receiver_id where a.group_id =".$mygrp_id."
ORDER BY count1 DESC";
答案 4 :(得分:1)
试试这个
SELECT count(receiver_id) as total_receiver FROM gr_group_memberships
INNER JOIN gr_group on gr_group_memberships.group_id = gr_group.id
GROUP BY gr_group_memberships.receiver_id
ORDER BY gr_group_memberships.receiver_id DESC
我认为它会按你想要的方式运作