最近看到一个面试题,是关于mysql的多表查询并排序分组的
题目如下:
Music表包含所有歌曲信息,每首歌曲尤其对应的Id,Name,Year和Singer Id。
+----+---------+--------+-----------+
+----+---------+--------+-----------+
Singer表包含所有歌手信息
+----+----------+
+----+----------+
请编写一个SQL查询语句,找出每个歌手年份最新的一首歌曲名字
+------------+----------+--------+
+------------+----------+--------+
建表语句
-- Music表包含所有歌曲信息,每首歌曲尤其对应的Id,Name,Year和Singer Id
CREATE TABLE music(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(20),
`year` INT,
sign_id INT
)
INSERT INTO music(id,name,year,sign_id) VALUES(null,'七里香',2003,1),
INSERT INTO music(id,name,year,sign_id) VALUES(null,'吻别',2000,2)
INSERT INTO music(id,name,year,sign_id) VALUES(null,'如果爱',2001,2)
INSERT INTO music(id,name,year,sign_id) VALUES(null,'菊花台',2005,1)
-- Singer表包含所有歌手信息
CREATE TABLE signer(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(20)
)
INSERT INTO signer(id,name) VALUES(null,'周杰伦')
INSERT INTO signer(id,name) VALUES(null,'张学友')
查询语句
SELECT
s. NAME AS Signer,
m. NAME,
m. YEAR
FROM
signer s
INNER JOIN (
SELECT
*
FROM
music
ORDER BY
`year` DESC
) AS m ON m.sign_id = s.id
GROUP BY
s.id
欢迎关注我的个人博客 https://myblog.52fun.fun/
转载:https://blog.csdn.net/yb233yb/article/details/101292030
查看评论