Travesty3
Travesty3

Reputation: 14479

Selecting a default value if an entry doesn't exist

I have three tables...users, user_info, and quota_levels. They look like this:

CREATE TABLE users (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(31) NOT NULL,
    password VARCHAR(33) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE user_info (
    userID INT UNSIGNED NOT NULL,
    firstName VARCHAR(32),
    lastName VARCHAR(32),
    phone CHAR(14),
    address VARCHAR(128),
    birthdate DATE,
    misc TEXT,
    quotaLevel VARCHAR(32),
    PRIMARY KEY (userID)
);

CREATE TABLE quota_levels (
    quotaLevel VARCHAR(32) NOT NULL,
    quota1 INT NOT NULL,
    quota2 INT NOT NULL,
    PRIMARY KEY (level)
);

Every user will have an entry in the users table, but not necessarily in the user_info table. Each user in the user_info table has a quotaLevel corresponding to the quotaLevel column in the quota_levels table. Possible values for quotaLevel are BRONZE, SILVER, GOLD, and PLATINUM.

I could go into a long explanation of why it is set up this way, but it would be quicker to just say that this structure cannot be changed.

If the user exists, I want to get the quota1 value of their quotaLevel. If the user doesn't exist, the quota1 value for BRONZE should be returned.

I want to do this with ONE query. Can it be done and how?

Upvotes: 0

Views: 662

Answers (1)

Joe Stefanelli
Joe Stefanelli

Reputation: 135858

SELECT u.Name, 
       COALESCE(ql.quota1, (SELECT quota1 FROM quota_level WHERE quotaLevel = 'BRONZE'))
    FROM users u
        LEFT JOIN user_info ui  
            INNER JOIN quota_level ql
                ON ui.quotaLevel = ql.quotaLevel              
            ON u.id = ui.userID

Upvotes: 2

Related Questions