[英]How to select rows from one table and order it by the sum of a column from another table?
In MySQL, I have two tables. 在MySQL中,我有两个表。 First is members.
首先是会员。 Second is member_experience.
其次是member_experience。 The member_experience table contains values of all the XP that members earn and what they get it for.
member_experience表包含成员赚取的所有XP的值以及获取的价格。 I want to write a query that selects members and orders results by the total of their xp.
我想编写一个查询,以选择成员并按其xp的总数对结果进行排序。 The query that I have written doesn't return any results.
我编写的查询未返回任何结果。
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;
This is my current query: 这是我当前的查询:
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";
This will do the stuff: 这将完成以下工作:
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
try this: 尝试这个:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.