I would like to do an outer join on a one-to-many relationship (using SQL or Hibernate), am I trying a wrong syntax, or is it impossible by design ?
Let’s take a simple example : a user is able to change values for parameters. For parameters without user value, the default value is used :
Table **PARAMETER** :
PAR_ID
PAR_NAME
PAR_DEFAULT_VALUE
Table **USER_PARAMETER** :
UP_ID
UP_PAR_ID
UP_US_ID
UP_CUSTOM_VALUE
Table **USER** :
US_ID
US_LOGIN
For a given user, I would like to list all parameters with their default value and their custom value if the user has given one (and “null” if it hasn’t any custom value for this user).
I’ve tried the following request, but it returns nothing if the user has no custom values :
SELECT PAR_NAME, PAR_DEFAULT_VALUE, UP_CUSTOM_VALUE
FROM PARAMETER
LEFT JOIN USER_PARAMETER on UP_PAR_ID = PAR_ID
WHERE UP_US_ID = 1
I would have expected PAR_NAME and PAR_DEFAULT_VALUE filled for each existing parameter, and UP_CUSTOM_VALUE filled for user customized parameters (and “null” for other parameters).
Move the condition
us_id = 1from thewhereclause to theonclause:This will cause the condition to be applied as part of the
left join, which will only filter out rows from the right side table. Thewhereclause doesn’t know about left or right.Look at this example data to see why the
wherecondition would filter out all rows without a custom value: