Select from other table if value exist

不打扰是莪最后的温柔 提交于 2019-12-04 19:48:30
select r.id,
     IF(c.name != '',c.name,r.name) as name,
     r.age 
 FROM Records r 
 LEFT JOIN Clients c ON c.id = r.id 
 GROUP BY c.id

Use above query.

EDITED:

  SELECT t.id, t.name, t.age FROM 
(
    (
        SELECT r.id,
        CASE WHEN c.name <> '' THEN c.name ELSE r.name END  as name,
        r.age 
        FROM Records r 
        LEFT JOIN Clients c ON c.id = r.id
    )
    UNION 
    (
        SELECT c.id, c.name, null as age FROM Clients c where c.id NOT IN (select id from Records)
    )
) as t ORDER BY t.id 

Use this query.

please try,hope this will work..

select c.id,
IF(NAME='',(select name from Records where id = c.id),'')
If(NAME=NULL,(select name from Records where id = c.id),NULL)
Else c.NAME
from client c;

cheers!!!

    select case when a.id <> '' then a.id else b.id end as id ,
case when a.name <> '' then a.name else b.name end as name,a.age
 from records a 
full outer join clients b on a.Id = b.id
order by a.id

Use COALECSE to get the first not-null value:

select id, coalesce(clients.name, records.name) as correct_name, records.age
from records
join clients using (id);

EDIT: In case not existing names are stored as '' instead of NULL use:

select id, case when clients.name = '' then records.name else clients.name end as correct_name, records.age
from records
join clients using (id);

Of course you can also react on both '' and NULL by asking

when clients.name = '' or clients.name is null then

See http://www.sqlfiddle.com/#!2/7e007/36.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!