views:

405

answers:

1

My setup is as follows:

Table 'data': 'title','body',...,'user_id',...  
Table 'users': 'user_id','some_val'...

Basically I want to somehow join the tables 'data' and 'users' on the user_id field so that I can pull 'some_val' from the 'users' table. My problem is that not every user_id in the 'data' table has a corresponding entry in the 'users' table.

With codeigniter/php I ultimately want to assemble a results array of values containing all the 'some_vals' from the 'users' table joining data.user_id = users.user_id. BUT when there exists a user_id in the data table but NOT in the users table, I want to insert some default value into my results array (and hopefully this array can be in the same order as the user_id's in the data table).

Hopefully this wasn't too unclear. Any ideas?

+2  A: 

What you'll want to do is what's called a left join. Essentially, this takes all of the rows of data and matches up the users table. Except, if data doesn't have a matching user_id, it just loads null for those columns. In order to deal with those nulls, you can use the coalesce function, which replaces a null with some value (could be 1234 if it's numeric, but I just chose 'DefaultVal' for demo purposes).

Anyway, it all comes together like so:

select
    coalesce(u.some_val, 'DefaultVal') as some_val
from
    data d
    left join users u on
        d.user_id = u.user_id
Eric
thanks for the responsequickly looking at that query - wouldn't I need to do 'from data d, users u ..'?
es11
Nope. `from data d, users u` is shorthand for saying `from data d inner join users u on ...`. In this case, we're using a `left join`, not an `inner join`. An `inner join` will get you *only* the data rows with a valid `user_id`. A `left join` will get you *all* rows, and return `null` for the `users` columns that don't match `data`'s `user_id`.
Eric
oh nevermind, I read it more carefully and what I said doesn't makes sense..thanks for the help! didnt know about the coalesce function..
es11
Glad I could help. The `coalesce` function is in practically every RDBMS, and it is phenomenally useful. So are `left join`s. Both are concepts that are imperative for more advanced SQL. Also, if this helps you, please mark it as an answer/upvote it for future viewers. Also, I happen to like that number next to my name go up, so that's not an entirely altruistic motive :)
Eric