说我有一对多的关系,比如一个歌手表,每个人都唱过多首歌: DROP TABLE歌手; CREATE TABLE歌手( id bigint not null auto_increment, name varchar(255)not null, PRIMARY KEY(id) );
INSERT INTO singers (name) VALUES ('Joe'), ('Bob');
DROP TABLE songs;
CREATE TABLE songs (
id bigint not null auto_increment,
singer_id bigint not null,
name varchar(255) not null,
PRIMARY KEY (id)
);
INSERT INTO songs (singer_id, name) VALUES (1, "foo"), (2, "bar"), (1, "baz"), (2, "quux");
假设歌曲行按时间顺序正确写出,例如我可以找到Joe与查询一起唱的最新歌曲
SELECT * FROM songs WHERE singer_id = 1 ORDER BY id DESC LIMIT 1;
现在,假设我想创建一个MySQL视图,其中包含每个歌手的一行以及该歌手演唱的最新歌曲。换句话说,一个看起来像这样的表:
singer_id singer_name song_id song_name
1 Joe 3 baz
2 Bob 4 quux
似乎这需要将上面的ORDER BY / LIMIT子句以某种方式集成到视图构造/连接逻辑中 - 但我无法弄清楚如何。这可能吗?
答案 0 :(得分:3)
select si.id, si.name, so.name, so.id
from singers si
inner join songs so on so.singer_id = si.id
where so.id = (select max(songs.id) from songs where songs.singer_id=si.id)
答案 1 :(得分:1)
我宁愿使用GROUP BY来做这种事情,所以这是我的解决方案:
(我为了方便而发表意见,但你不必这样做)
CREATE VIEW lastsongs AS SELECT singers.id, singers.name, MAX(songs.id) AS lastsong FROM singers JOIN songs ON songs.singer_id = singers.id GROUP BY singers.id, singers.name; CREATE VIEW lastsongnames AS SELECT lastsongs.name, songs.name AS songname FROM lastsongs JOIN songs ON songs.id = lastsongs.lastsong; SELECT name, songname FROM lastsongnames;