2013-08-28 76 views
0

在MySQL中,我有兩個表。首先是成員。其次是member_experience。 member_experience表格包含所有成員獲得的XP值以及他們獲得的值。我想編寫一個查詢來選擇成員並按xp的總數排序結果。我寫的查詢不會返回任何結果。如何從一個表中選擇行並按另一個表中列的總和進行排序?

 
CREATE TABLE IF NOT EXISTS `members` (
    `member_id` int(15) NOT NULL AUTO_INCREMENT, 
    `group_id` int(15) NOT NULL, 
    `display_name` text NOT NULL, 
    `email_address` text NOT NULL, 
    `password` text NOT NULL, 
    `status` tinyint(1) NOT NULL, 
    `activation_code` varchar(16) NOT NULL, 
    `date_joined` text NOT NULL 
    PRIMARY KEY (`member_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

CREATE TABLE IF NOT EXISTS `member_experience` (
    `experience_id` int(15) NOT NULL AUTO_INCREMENT, 
    `member_id` int(15) NOT NULL, 
    `value` mediumint(6) NOT NULL, 
    `description` text NOT NULL, 
    `date_earned` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', 
    PRIMARY KEY (`experience_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

這是我當前的查詢:

 

     SELECT 
      m.member_id, 
      xp.member_id, SUM(xp.value) AS total_xp 
     FROM members AS m 
     LEFT JOIN member_experience AS xp ON (xp.member_id = m.member_id) 
     ORDER BY total_xp"; 

回答

0

這將做的東西:

SELECT 
    members.member_id, 
    total_xp.sum_xp 
FROM 
    members 
    LEFT JOIN 
    (SELECT 
     member_id, 
     SUM(value) AS sum_xp 
    FROM 
     member_experience 
    GROUP BY 
     member_id) AS total_xp 
    ON members.member_id = total_xp.member_id 
ORDER BY 
    total_xp.sum_xp 
0

試試這個:

SELECT 
    m.member_id, 
    xp.member_id, SUM(xp.value) AS total_xp 
FROM 
    members AS m 
LEFT JOIN 
    member_experience AS xp ON xp.member_id = m.member_id 
GROUP BY 
    m.member_id 
ORDER BY 
    SUM(xp.value) 
相關問題