簡體   English   中英

使用mysql在兩行中獲取記錄

[英]Get records in two lines with mysql

我在多個表中有一些數據,我想加入該表,並需要顯示結果,因為下面的多個記錄是表結構

          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中使用查詢來實現此功能,並期望獲得建議?

使用UNION

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

嘗試使用左和可樂

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM