简体   繁体   中英

sql select statement with 3 tables?

I have 3 related tables in the database, the table is A, B & C table structure as below

table A

id | name_A 
--- + --------- 
1 | Endru 
2 | maz 
3 | Hudson 

table B

id | name_B 
----- + ------- 
10 | Food 
11 | clothes 

table C

id | status 
--- + ------- 
1 | exist 
10 | exist 
3 | none 

I want to produce like this

id | name_A | name_B | status 
------------------------------------------ 
1 | Endru | null | exist 
10 | null | food | exist 
3 | hudson | null | none 

how do I achieve, I have tried using inner and left outer join but no success.

thanks

You can do this using union all and aggregation:

select id, max(name_a) as name_a, max(name_b) as name_b,
       coalesce(max(status), 'none') as status
from (select id, name_a, NULL as name_b, NULL as status
      from tableA
      union all
      select id, NULL, name_b, NULL
      from tableB
      union all
      select id, NULL, NULL as name_b, status
      from tableC
     ) abc
group by id;

Try this query:

SELECT `id`, `name_A`, `name_B`, `status`
FROM `tableC`
LEFT JOIN  `tableA` USING (`id`)
LEFT JOIN  `tableB` USING (`id`)

I think the following query will fetch what you need

SELECT tableC.id, TableA.name_A,TableB.name_B,tableC.status
FROM tableC 
LEFT JOIN TableA on TableC.id = TableA .id
LEFT JOIN TableB on TableC.id = TableB .id

Use This Query :

SELECT tbc.Id,tba.Name_A,tbb.NameB,tbc.[Status] 
FROM tablec tbc 
INNER JOIN tablea tba on tba.Id = tbc.Id
INNER JOIN tableb tbb on tbb.Id = tbc.Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM