建议更好的MySQL查询

时间:2012-08-29 20:13:55

标签: mysql sql joomla

当涉及到mysql查询时,我是一个相对的noob,所以请不要咬我的头。我正在尝试使用轮询扩展和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

1 个答案:

答案 0 :(得分:3)

目前,您无法将#__community_users加入#__users。这是一个更新的查询,其中隐式联接换出显式INNER JOIN,假设#__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.id中只有GROUP 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