简体   繁体   中英

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)

    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.

     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)?

I'm trying to get an accounts customs settings, as well as the LEFT JOIN the settings table for the default values & labels.

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.

remove your where condition put it with join on condition

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

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