一列中有多列

时间:2014-01-25 23:28:49

标签: sql view h2

我有一个管理我的音乐库的数据库,我将所有id3标签存储在数据库表中。数据模型如下所示:http://abload.de/img/modelq5sx3.png

CREATE TABLE Tracks (
    Track_ID INTEGER NOT NULL AUTO_INCREMENT,
    Title VARCHAR(255),
    Track_Year YEAR,
    Filename VARCHAR(255),
    Track_Length CHAR(5),
    Folder_ID INTEGER,
    Album_ID INTEGER,
    CONSTRAINT PK_Tracks PRIMARY KEY (Track_ID),
    UNIQUE Unique_Path (Folder_ID, Filename)
);

CREATE TABLE Artists (
    Artist_ID INTEGER NOT NULL AUTO_INCREMENT,
    Artist VARCHAR(50),
    CONSTRAINT PK_Artists PRIMARY KEY (Artist_ID),
    UNIQUE (Artist)
);

CREATE TABLE Albums (
    Album_ID INTEGER NOT NULL AUTO_INCREMENT,
    Album VARCHAR(100),
    AlbumArtist INTEGER,
    AlbumCover VARCHAR(100),
    CONSTRAINT PK_Albums PRIMARY KEY (Album_ID),
    UNIQUE (Album)
);

CREATE TABLE Tracks_Artists (
    Artist_ID INTEGER NOT NULL,
    Track_ID INTEGER NOT NULL,
    CONSTRAINT PK_Tracks_Artists PRIMARY KEY (Artist_ID, Track_ID)
);

所以我在单独的实体中有曲目,专辑和艺术家,在曲目和艺术家之间具有n:m关系,因为曲目可以由多个艺术家执行,而艺术家可以在多个曲目中执行。我这样做是为了按艺术家搜索曲目。 但是为了制作一个漂亮的曲目视图,我想让所有这些艺术家在每个轨道上都有一行,到目前为止我还没有管理过。我所能做的就是加入Album,每张专辑有一个专辑艺术家:

create or replace view v_c_tracks as SELECT t.traCK_ID,t.title,ar.arTIST,a.album 
FROM TRACKS t 
join albums a on t.album_id=a.album_id
join artists ar on a.albumartist=ar.artist_id 
order by t.title;

1 个答案:

答案 0 :(得分:0)

您需要加入track_artists表。然后,要在单行上获得结果,您需要按轨道聚合。将艺术家聚集在一起的关键是group_concat()

SELECT t.traCK_ID, t.title, group_concat(ar.artist) as artists, a.album 
FROM tracks t join
     albums a
     on t.album_id = a.album_id join
     track_artists ta
     on ta.track_id = track.track_id join
     artists ar
     on ta.artist_id = ar.artist_id 
group by t.traCK_ID, t.title, a.album
order by t.title;