使用mysql获取两行记录

ezykj2lf  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(276)

我在多个表中有一些数据,我想连接这些表,并且需要将结果显示为下面的表结构中的多个记录

main_table                           
   id     name   height                
   1      test1  5.2                     
   2      test2  4.6                    

          child_table                         
   id  main_table_id  name   height     
   1       1          test3  5.3         
   2       1          test4  4.5

期望结果如

id  name    height   

   1   test1   5.2      
   1   test3   5.3
   1   test4   4.5

如何在mysql中使用查询来实现这一点?

pn9klfpd

pn9klfpd1#

尝试使用left和colasce

select maintable.id,COALESCE(maintable.name,childtable.name) as name,
COALESCE(maintable.height,childtable.height) 
from maintable left join childtable
on maintable.id=childtable.main_table_id
where maintable.id=1
qyswt5oh

qyswt5oh2#

使用并集

SELECT id, name, height 
FROM main_table 
WHERE id = 1

UNION 

SELECT main_table_id as id, name, height 
FROM child_table 
WHERE main_table_id = 1

相关问题