简体   繁体   English

sql left join:无论条件如何,始终返回左表列

[英]sql left join: always return left table columns, no matter the condition

I've got two tables: 我有两个桌子:

account_settings 帐号设定

This table uses the settings.id field as an FK to store the users custom settings (the settings table below has the name of the setting and the default value) 该表使用settings.id字段作为FK来存储用户自定义设置(下面的设置表具有设置名称和默认值)

    Column    |           Type           |                           Modifiers
--------------+--------------------------+---------------------------------------------------------------
 id           | integer                  | not null default nextval('account_settings_id_seq'::regclass)
 user_id      | uuid                     | not null
 setting_id   | integer                  | not null
 value        | text                     |

settings: 设置:

This table holds all the available settings. 该表包含所有可用设置。 Eg weekly_email, app_notifications, block_user, etc...It also holds the default value for each of them. 例如weekly_email,app_notifications,block_user等...它还保留了每个参数的默认值。

     Column     |           Type           |                       Modifiers
----------------+--------------------------+-------------------------------------------------------
 id             | integer                  | not null default nextval('settings_id_seq'::regclass)
 key            | text                     | not null
 frontend_label | text                     |
 default_value  | text                     |

I'm using the property bag schema design to store user settings for our app! 我正在使用属性包模式设计来存储我们应用程序的用户设置! It will include notification settings, email settings, etc... 它将包括通知设置,电子邮件设置等...

Is it possible to have a query that always returns the settings columns, even when you add a where statement in there (the where statement is there for querying for the account_settings by user_id)? 即使在其中添加where语句(那里的where语句用于通过user_id查询account_settings),是否有可能始终返回settings列的查询?

I'm trying to get an accounts customs settings, as well as the LEFT JOIN the settings table for the default values & labels. 我正在尝试获取帐户海关设置以及默认值和标签的左加入settings表。

Here is what I have now: 这是我现在所拥有的:

select account_settings.*, settings.* from settings 
LEFT JOIN account_settings 
ON settings.id = account_settings.id 
where account_settings.user_id = 'UUID_HERE';

This won't return the the settings table values though! 但是,这不会返回设置表的值! It will only return the settings values if the settings.id column is referenced in the account_settings.setting_id column. 如果在account_settings.setting_id列中引用了settings.id列,则只会返回设置值。

remove your where condition put it with join on condition 删除您的where条件,并加入条件条件

 select account_settings.*, settings.* from settings 
    LEFT JOIN account_settings 
    ON settings.id = account_settings.id and account_settings.user_id = 'UUID_HERE';

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

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