创建具有多个表的视图

daupos2t  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(355)

创建包含多个表和连接表的视图时遇到问题。
这就是我目前的处境:

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。我应该做子查询而不是连接吗?我的结果是空集。这个作业的问题如下:
创建一个视图,其中包含所有录音的标题和销售额、各自艺术家的姓名以及录音类型的名称。按流派名称的字母顺序排序。在同一类型中,按艺术家姓名的字母顺序排序。在同一艺术家中,按销售额排序(最高优先)。不要包含空标题、流派或艺术家名称。视图必须有4列。

8yparm6h

8yparm6h1#

您将需要一个与下一个类似的查询,使用 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;

最后一步:
不要包含空标题、流派或艺术家名称
你可以在一个 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;

相关问题