3

当涉及到 mysql 查询时,我是一个相对的菜鸟,所以请不要咬我的头。我正在尝试使用投票扩展和 Jomsocial 制作“Top Poller”模块。我想按他们创建的民意调查数量显示前 5 名用户。这是数据表结构(以及重要部分)

#__users
-id
-name
-username

#_jcp_polls
-created_by (this is the same as #users.id)

#__community_users
-thumb
-avatar

这是我的查询

$db = JFactory::getDBO();

$query = "SELECT u.id, u.username, u.name, c.thumb, c.avatar,COUNT(p.created_by) as total
      FROM #__users u, #__community_users c, #__jcp_polls p 
      WHERE u.id = p.created_by
      GROUP by u.id
  ORDER BY total DESC
      LIMIT $user_count
     ";

$db->setQuery($query);
$rows = $db->loadObjectList();

我可以在 foreach 循环中显示用户表字段,例如

foreach($rows as $row){
 echo $row->name
}

我以为我可以使用$row->avatar,但它不起作用。有人可以建议一个查询,让我可以显示#__community_users表中的字段以及#__users table?并且仍然保持排名从#__jcp_polls table

4

1 回答 1

3

目前,您没有加入#__community_users的条件#__users。这是一个更新的查询,其中隐式连接换成了显式INNER JOINs,假设#__community_users有一列user_id#__users.id. 在上面的表结构中,您没有#__community_users#__users. 没有一个,您就无法将化身与用户联系起来。

SELECT 
  u.id, u.username, u.name, c.thumb, c.avatar,COUNT(p.created_by) as total
FROM 
  #__users u 
  /* Supply the correct column name for c.user_id */
  JOIN #__community_users c ON u.id = c.user_id
  /* LEFT JOIN used to list 0 for users who have no polls */
  LEFT JOIN #__jcp_polls p ON u.id = p.created_by
GROUP by u.id
ORDER BY total DESC
LIMIT $user_count

如果用户可能没有头像,请使用LEFT JOIN反对#__community_users

SELECT 
  u.id, u.username, u.name, c.thumb, c.avatar,COUNT(p.created_by) as total
FROM 
  #__users u 
  /* Supply the correct column name for c.user_id */
  LEFT JOIN #__community_users c ON u.id = c.user_id
  /* LEFT JOIN used to list 0 for users who have no polls */
  LEFT JOIN #__jcp_polls p ON u.id = p.created_by
GROUP by u.id
ORDER BY total DESC
LIMIT $user_count

您的语法虽然对 MySQL 有效,但并非普遍有效,因为您在SELECT列表中有多个列,但仅u.idGROUP BY. 更便携的查询版本如下所示:

SELECT
  u.id, u.username, u.name, c.thumb, c.avatar, p.total
FROM
  #__users u 
  LEFT JOIN #__community_users c ON u.id = c.user_id
  /* Left Join against a subquery that returns count per user */
  LEFT JOIN (SELECT created_by, COUNT(*) AS total FROM #__jcp_polls GROUP BY created_by) p ON u.id = p.created_by
ORDER BY total DESC
LIMIT $user_count
于 2012-08-29T20:19:16.433 回答