简体   繁体   English

一对多关系的外部联接(Hibernate / SQL)

[英]Outer join on a one-to-many relationship (Hibernate / SQL)

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 ? 我想对一对多关系(使用SQL或Hibernate)进行外部联接,我是否尝试使用错误的语法,或者设计是否可行?

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). 对于给定的用户,如果用户给定了一个参数,我想列出所有参数及其默认值和自定义值(如果该用户没有任何自定义值,则为“ null”)。

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). 我希望为每个现有参数填充PAR_NAME和PAR_DEFAULT_VALUE,为用户自定义参数填充UP_CUSTOM_VALUE(对于其他参数填充为“ null”)。

Move the condition us_id = 1 from the where clause to the on clause: 将条件us_id = 1where子句移到on子句:

select  *
from    parameter p
left join
        user_parameter up
on      up.up_par_id = p.par_id
        and up.up_us_id = 1

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. 这将导致该条件被应用为left join一部分,该left join仅会过滤掉右侧表中的行。 The where clause doesn't know about left or right. where子句不了解left或right。

Look at this example data to see why the where condition would filter out all rows without a custom value: 查看此示例数据,以了解where条件为何会过滤掉没有自定义值的所有行:

par_id   default_value   user_id  custom_value
1        1              1       2             --> works
2        1              null    null          --> filtered out by UP_US_ID = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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