MYSQL-创建具有多个表的视图

时间:2018-11-14 02:05:18

标签: mysql

我在创建具有多个表和联结表的视图时遇到麻烦。

这是我目前所在的位置:

CREATE VIEW music_view AS 
SELECT recordings.rec_title, 
recordings.sales, 
artists.name as 'artists', 
genres.name as 'genres'
FROM 
recordings
JOIN artists
JOIN genres
JOIN rec_artist
WHERE artists.id = rec_artist.id
AND recordings.rec_id = rec_artist.rec_id
AND genres.id = recordings.genre_id;

表架构:

recordings
rec_title (varchar)
rec_id (Primary Key)
sales (dec)
genre_id (Foreign Key)

genres
id (primary key)
name (varchar)

artists
id (primary key)
name (varchar)

rec_artist (junction table)
artist_id (primary key) 
rec_id (primary key)

我对下一步工作有些困惑,但仍在弄清楚MYSQL。我应该执行子查询而不是联接吗?我的结果是空集。 对于此特定的作业,问题如下:

创建一个视图,其中包含所有唱片的标题和销售,其各自艺术家的姓名以及唱片类型的名称。按类型名称按字母顺序排序。在同一类型中,按艺术家姓名的字母顺序排序。在同一位艺术家中,按销售额排序(最高者)。 不要包括NULL标题,流派或艺术家名称。 您的视图必须有4列。

1 个答案:

答案 0 :(得分:1)

您将需要一个类似于下一个查询的查询,使用inner joins将表联接到足够的列上:

CREATE VIEW music_view AS 
SELECT
    r.rec_title AS 'title',
    r.sales AS 'sales',
    a.name AS 'artist', 
    g.name AS 'genre'
FROM
    recordings AS r
INNER JOIN
    rec_artists AS ra ON ra.rec_id = r.rec_id
INNER JOIN
    artists AS a ON a.id = ra.artist_id
INNER JOIN
    genres AS g ON g.id = r.genre_id
ORDER BY
    'genre' ASC, 'artist' ASC, 'sales' DESC;

最后一步:

  

请勿包含NULL标题,流派或艺术家名称

您可以在where子句中添加一些限制。像这样:

CREATE VIEW music_view AS 
SELECT
    r.rec_title AS 'title',
    r.sales AS 'sales',
    a.name AS 'artist', 
    g.name AS 'genre'
FROM
    recordings AS r
INNER JOIN
    rec_artists AS ra ON ra.rec_id = r.rec_id
INNER JOIN
    artists AS a ON a.id = ra.artist_id
INNER JOIN
    genres AS g ON g.id = r.genre_id
WHERE
    r.rec_title IS NOT NULL
AND
    a.name IS NOT NULL
AND
    g.name IS NOT NULL
ORDER BY
    'genre' ASC, 'artist' ASC, 'sales' DESC;