简体   繁体   中英

How to list all users, and use a sub-query in an outer join

I want to return all users, and if they went to a conference I want to return the conference information. The @ConferenceID will be a parameter.

SELECT 
    U.UserId,
    O.ConferenceName,
    O.LocationName
FROM Users

My outer join will need something like:

SELECT *
FROM Conferences C
    INNER JOIN Locations L ON C.LocationId = L.LocationId
WHERE UserId = ??
     AND C.ConferenceID = @ConferenceID

Is it possible to perform an outer join so that all users are returned, and then optionally display the conference info if they went to one?

I tried this:

   SELECT 
    U.*,
    oj.

FROM Users U

    OUTER JOIN ( 
        SELECT c.ConferenceName, L.LocationName
        FROM Conferences C
            INNER JOIN Locations L ON C.LocationId = L.LocationId
        WHERE C.ConferenceID = @ConferenceID
    ) AS oj.UserID = U.UserID

But I get an error

The multi-part identifier "U.UserId" could not be bound.

DDL:

User
-UserId


Conference
-ConferenceID
-UserID
-LocationId

Locations
-LocationID

Yes, you can use an outer join, in particular a LEFT JOIN , but you need to move the ConferenceID condition to the join clause, and you need to LEFT JOIN both tables.

SELECT U.UserId
     , C.ConferenceName
     , L.LocationName
  FROM Users U
  LEFT JOIN Conferences C ON C.ConferenceID = @ConferenceID
                         AND C.UserID = U.UserId
  LEFT JOIN Locations L ON L.LocationID = C.LocationId

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