views:

216

answers:

2

Hi,

i'm trying to build a join, but I can't get it to work in MySQL, I know there must be a way.

I have two tables: 1. Setting and 2. User_Setting (and ofcourse User but that won't be needed here).

Structure

Setting.setting_id
Setting.description
Setting.value_type
Setting.default_value

User_Setting.user_id
User_Setting.setting_id
User_Setting.value

I want to select ALL Setting records, and join User_Setting where there is a value. Classical outer join i would believe?

I have this query:

SELECT
`User_Setting`.`user_id`,
`User_Setting`.`value`,
`Setting`.`setting_id`,
`Setting`.`default_value`,
`Setting`.`value_type`,
FROM
`User_Setting`
Right Join `Setting` ON `User_Setting`.`setting_id` = `Setting`.`setting_id`
WHERE
`User_Setting`.`user_id` IS NULL OR
`User_Setting`.`user_id` =  1;

But this doesn't work if a User with user_id 2 has a User_Setting record present for a certain setting_id, but the User with user_id 1 hasn't got that setting_id record stored...

Does anybody have a query where ALL settings will be retrieved, with user_id and value NULL if the User_Setting record doesn't exist?

+2  A: 

This (if you want to check that the user exists)

SELECT  `User_Setting`.`user_id`,
        `User_Setting`.`value`,
        `Setting`.`setting_id`,
        `Setting`.`default_value`,
        `Setting`.`value_type`,
FROM    user
CROSS JOIN
        setting
LEFT JOIN
        user_setting
ON      user_setting.user_id = user_id
        AND user_setting.setting_id = setting.setting_id
WHERE   user_id = 1

or this (if you don't want to check that the user exists):

SELECT  `User_Setting`.`user_id`,
        `User_Setting`.`value`,
        `Setting`.`setting_id`,
        `Setting`.`default_value`,
        `Setting`.`value_type`,
FROM    setting
LEFT JOIN
        user_setting
ON      user_setting.user_id = 1
        AND user_setting.setting_id = setting.setting_id
Quassnoi
great this works perfectly. Thanks!
Ropstah
A: 

I usually add a condition to the WHERE clause to check that the primary if in the table being joined is not null.

Jrgns