0

I am querying table a for each row's name, however, if the row has a bID value (this will be a foreign key to table b's id), I want to replace the name value from table a with table b. How can I do this?

table a
---------
id / bID (may be null) / name

table b
---------
id / name

SELECT a.id as id, a.name as name, a.bid
FROM `table a` as a
LEFT JOIN `table b` as b ON a.bID = b.id
ORDER BY id ASC

1 Answer 1

1

A simple ISNULL on the 'b' table's name should suffice. You could use COALESCE instead if you want which can also take multiple parameters, not just two as with ISNULL.

SELECT a.id as id, ISNULL(b.name, a.name) as name, a.bid
FROM `table a` as a
LEFT JOIN `table b` as b ON a.bID = b.id
ORDER BY id ASC
2
  • If that is the case then you must not be using MS SQL, which I assumed and you didn't mention in you question/tagging. I always assume MS SQL as that's what I mainly use unless the poster has specified otherwise. What RDMS are you using out of curiosity?
    – XN16
    Jan 16, 2014 at 16:19
  • My bad. I thought MySQL was the norm. I'm using MySQL.
    – ditto
    Jan 16, 2014 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.