Question

Here's what I'm trying to achieve : Select a person's or firm's name depending on the contact type.

Tables :

CONTACTS :               PEOPLE              FIRMS
- id                     - contact_id        - contact_id    
- type (person/firm)     - name              - name

I would like this kind of magic :

SELECT type 
FROM contacts 
WHERE contacts.id = 42;

SELECT model.name 
FROM contacts LEFT JOIN model ON model.contact_id = contacts.id 
WHERE contacts_id = 42 
AND model = CASE (WHEN type = "person" THEN "people" 
                  WHEN type = "firm" THEN "Firms" END); (Not sure this one works)

All in one query. Thanks !

Was it helpful?

Solution 2

Simply left join both tables; one of them will match id and type. Use COALESCE then to display the one name found.

select coalesce(p.name, f.name) as name
from contacts c
left join people p on p.contacts_id = c.id and c.type = 'person'
left join firms f on f.contacts_id = c.id and c.type = 'firm'
where c.id = 42;

OTHER TIPS

You could do like below, join two tables and then decide which column to use according to contacts.type.

SELECT 
  (CASE WHEN t1.type = 'person' THEN t2.name WHEN t1.type = 'firm' THEN t3.name) AS contact_name
FROM contacts t1
LEFT JOIN people t2 ON t1.id = t2.contact_id
LEFT JOIN firms t3 ON t1.id = t3.contact_id

You can use dynamic sql like this:

declare 
    @table_name nvarchar(20),
    @query nvarchar(max)

SELECT 
    @table_name = 
                    case type 
                        when 'person' then 'people'
                        when 'firm' then 'firms'
                    end
FROM contacts  
WHERE contacts.id = 42;


set @query = N'SELECT ' + @table_name + '.name ' +
                'FROM contacts LEFT JOIN model ON ' + @table_name + '.contact_id = contacts.id 
                WHERE contacts_id = 42 '

exec sp_executesql @query

Here is an alternative way without a join:

select 
  case when c.type = 'person' then
    (select name from people p where p.contacts_id = c.id)
  else
    (select name from firms f on f.contacts_id = c.id)
  end as name
from contacts c
where c.id = 42;

You see, there are many ways to address the problem. Just pick the one you find most readable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top