简体   繁体   中英

SQL query to select columns from subquery

I am trying to start using subqueries which to this point I haven't needed to. If I have these tables:

Books
--Id (Primary Key)
--Title (string)
--GenreId (Foreign Key)

and

Genre
--Id (Primary Key)
--Name (string)

I know that if I want to retrieve Title and Name, then I can run this query:

select b.Title, g.Name from Books b
join Genre g on b.GenreId=g.Id

What I am trying to do is understand the difference between that and this:

select b.Title from Books b
join (
    select g.Id, g.Name from Genre g
)
as ge
on b.GenreId=ge.Id
go

I want to know why the second query only gives me the Title column from Books and not the Id or Name columns from Genre? My question really is how can I turn the first query into a subquery and retrieve the same results? I want both Title from Books, and Name from Genre.

The second query only gives you the title because that is all you asked for.

The outermost select describes the result set you are getting. Other select s are used for the processing logic but don't affect the columns being returned.

尝试这个。

  select G.name, B.title from Books B left join Genre G On G.ID = B.GenreId

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