简体   繁体   中英

Can you have multiple inner joins with a where clause that only effects one of the joins?

This is my sql command:

SELECT GIG.GIG_DESCRIPTION, VENUES.VENUE_NAME, BAND.BAND_NAME, 
CASE WHEN GIG.USERID = 0 THEN '--CREATED BY THE BAND--' ELSE USERS.USERNAME END, 
GIG.GIG_DATE 
from GIG 
INNER JOIN VENUES ON GIG.VENUEID = VENUES.VENUEID 
INNER JOIN BAND ON GIG.BANDID = BAND.BANDID 
INNER JOIN USERS ON GIG.USERID = USERS.USERID 
WHERE GIG.USERID != 0 
AND GIG.GIGID=" + gigID;

I'm using this query to return some values for a java object. In the Gig table sometimes the userid will equal 0, I'm getting a null pointer exception when I try and return a row with the userid equal to 0. I think I can get rid of the error if that last inner join on the users isn't run if a certain condition isn't true. Can I use a where clause that only effects the last join? How would I do that?

I think that you need link the USERS table using a LEFT JOIN clause in order to not discard the results with userid = 0 and remove the GIG.USERID != 0 on the WHERE clause:

SELECT GIG.GIG_DESCRIPTION, VENUES.VENUE_NAME, BAND.BAND_NAME, 
CASE WHEN GIG.USERID = 0 THEN '--CREATED BY THE BAND--' ELSE
USERS.USERNAME END, 
GIG.GIG_DATE 
from GIG 
INNER JOIN VENUES ON GIG.VENUEID = VENUES.VENUEID 
INNER JOIN BAND ON GIG.BANDID = BAND.BANDID 
LEFT JOIN USERS ON GIG.USERID = USERS.USERID 
WHERE GIG.GIGID=" + gigID;

You can have multiple conditions in a join, try something like

INNER JOIN USERS ON GIG.USERID = USERS.USERID AND GIG.USERID != 0
WHERE ...

The where clause is applied to the result of the joins, so it can't be limited to just the last inner join .

You can add your condition to the where clause, of course. But you should keep in mind that it will affect the whole join.

I would suggest you add your condition to your on clause for the particular join.

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