mysql資料庫
Table: Student
序號, 名字, 年齡
00001, 張三, 16
00002, 李四, 13
00003, 王二, 15
要如何依年齡大排到小, 然後取前2筆資料, 年齡相加呢? (期望結果: 張三和王二年齡加總)
select sum(年齡) from Student order by 年齡 desc limit 2
但是程式會將所有人的年齡相加, limit 2似乎不起作用, 該怎麼寫呢?
SELECT
SUM(o.年齡)
FROM
(SELECT
`年齡`
FROM
`Student`
ORDER BY `年齡` DESC
LIMIT 2) AS o;
SQL語法有優先順序,LIMIT算後面執行所以會碰到這問題,之前被坑過一次。
再select一次就得了
Schema (MySQL v8.0)
CREATE TABLE test (
id int NOT NULL AUTO_INCREMENT ,
name varchar(50),
age int ,
PRIMARY KEY (id)
);
INSERT INTO test (name,age) VALUE ('張三',45) ;
INSERT INTO test (name,age) VALUE ('李四',50) ;
INSERT INTO test (name,age) VALUE ('小王',24) ;
INSERT INTO test (name,age) VALUE ('老許',54) ;
Query #1
SELECT sum(age) FROM
(SELECT AGE FROM test ORDER BY AGE LIMIT 2) as AGE;
sum(age) |
---|
69 |