简体   繁体   中英

Combine SQL View with Left Outer Join Query

I have a view called Home:

CREATE VIEW `skohr`.`Home` AS
Select Song_OID, Song_Name, Album_Name, Artist_First_Name, Artist_Last_Name, Band_Name, Genre, Album_Art_File_Path
From Song, Album, Artist, Track_Number, Made
Where Song_OID = Track_Number.Song_OID_FK AND Album_OID=Track_Number.Album_OID_FK AND Album_OID=Made.Album_OID_FK AND Artist_OID=Made.Artist_OID_FK
ORDER BY Song_Name Asc

I ran the following query on the view to get my desired table:

Select DISTINCT * From Home LEFT OUTER JOIN (SELECT * FROM Song_Setting, user WHERE User_OID=User_OID_FK) AS UserSongs
ON Song_OID=Song_OID_FK

How do I combine the two separate queries into one to create a single view?

try just creating the View

CREATE VIEW `skohr`.`MyNewView` AS

Select DISTINCT * From Home h
LEFT OUTER JOIN Song_Setting x
    ON h.Song_OID_FK = x.Song_OID
INNER JOIN user u
    ON u.User_OID = x.User_OID_FK  

::Response to comment requesting MySQL version::

I don't specifically use MySQL today, but is there any reason you could not use a subquery as you have for your other data set? Something like this:

Select DISTINCT * From 
(
    Select Song_OID, Song_Name, Album_Name, Artist_First_Name, Artist_Last_Name, Band_Name, Genre, Album_Art_File_Path
    From Song, Album, Artist, Track_Number, Made
    Where Song_OID = Track_Number.Song_OID_FK AND Album_OID=Track_Number.Album_OID_FK AND Album_OID=Made.Album_OID_FK AND Artist_OID=Made.Artist_OID_FK
) as a
LEFT OUTER JOIN (SELECT * FROM Song_Setting, user WHERE User_OID=User_OID_FK) AS b
ON a.Song_OID=b.Song_OID_FK

And if that will not work for MySQL, I think you may be left with looking into using temporary / in-memory tables. So look into creating temp tables in MySQL, create a temp table and fill it with the sub-query I captured in a CTE below, then join that into your other query.

If this is SQL Server, you can utilize CTEs

Just drop the following code into a View and it should give you what you want.

WITH Home AS 
(
Select Song_OID, Song_Name, Album_Name, Artist_First_Name, Artist_Last_Name, Band_Name, Genre, Album_Art_File_Path
From Song, Album, Artist, Track_Number, Made
Where Song_OID = Track_Number.Song_OID_FK AND Album_OID=Track_Number.Album_OID_FK AND Album_OID=Made.Album_OID_FK AND Artist_OID=Made.Artist_OID_FK
)
Select DISTINCT * From Home 
LEFT OUTER JOIN (SELECT * FROM Song_Setting, user WHERE User_OID=User_OID_FK) AS UserSongs
ON Song_OID=Song_OID_FK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM