2012-08-29 90 views
3

我是一個相對noob,當涉及到mysql查詢,所以請不要咬我的頭。我正在嘗試使用輪詢擴展和Jomsocial創建「頂級輪詢」模塊。我想通過他們創建的民意調查顯示前5名用戶。下面是數據表結構(以及重要的部分)建議更好的MySQL查詢

#__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

回答

3

目前,您沒有條件加入#__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 

如果有可能對用戶不要有頭像,使用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列表中,但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 
+1

+1有關詳細的解釋和多種解決方案。 – Lodder

+0

嘿,謝謝你花時間解釋。看起來不錯,我現在就去試試看 – Brad