数据库
首页 > 数据库> > 提出更好的MySQL查询

提出更好的MySQL查询

作者:互联网

我是一个相对的菜鸟,当涉及到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表中的字段吗?仍然保留#__jcp_polls表中的排名?

解决方法:

目前,您没有条件将#__community_users加入到#__users.假设#__community_users具有与#__ users.id相关的user_id列,这是一个更新的查询,其中隐式联接被换为显式的INNER JOIN.在上面的表格结构中,没有与#__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

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

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列表中有多个列,而在GROUP BY中只有u.id.查询的一个更可移植的版本如下所示:

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

标签:joomla,sql,mysql
来源: https://codeday.me/bug/20191127/2076360.html