2015-09-27 67 views
0
Fruits    Animals 
+------------------+------------------------+ 
| fruID fruDesc | animalID animalDesc | 
|     |      | 
| 0  Unknown | 0   Unknown  | 
| 1  Apple  | 1   Bird  | 
| 2  Banana  | 2   Tiger  | 
| 3  Microsoft | 3   Etc   | 
+------------------+------------------------+ 
NoBrain 
+-------------------------------------------+ 
| someField fruID animalID dateRecorded | 
|           | 
| 0   3  2   now   | 
+-------------------------------------------+ 

我在使用MySQL並試圖編寫一個程序,該程序接受兩個預期爲fruDesc和animalDesc的文本字段,查找其相關的ID並將這些列插入表中。從兩個表格中選擇插入表格時沒有任何關係

在上面的情形中,我應該能夠CALL cool_proc(「香蕉」,「虎」,「reallydoesntmatter」)並且應插入NoBrain TBL對應行:

NoBrain 
+-----------------------------------------------+ 
| someField fruID animalID dateRecorded  | 
|            | 
| 2   2  2   reallydoesntmatter| 
+-----------------------------------------------+ 

我可以完成此通過做多個查詢和選擇,但我想知道是否有一個單一的查詢做到這一點?沒有加入(當有很多行記錄時,加入是很強壯的,我想 - )

另外你可能已經注意到,如果沒有匹配,我希望proc被使用ID默認爲0。假設我可以用COALESCE

EDITS實現這一點:假設someField是自動遞增

+0

在NoBrain,做你想做的日期/時間值'NOW'或文本值'reallydoesntmatter'?無論哪種情況,您都可以在下面輕鬆修復Gordon Linoff的解決方案。 –

回答

1

這是一個有點棘手,因爲你讓沒有比賽。在其他數據庫中,您將使用full outer join。在MySQL中,你可以使用union all和聚集:

insert into nobrain(fruid, aniamlid, daterecorded) 
    select max(f.fruid), max(animalid), now() 
    from ((select f.fruid, NULL as animalid, NULL as animalDesc 
      fruits f 
      where f.frudesc = 'Banana' 
     ) union all 
      (select a.animalid, NULL, animalDesc 
      from animals a 
      where a.animalDesc = 'Tiger' 
     ) 
     ) af; 
+0

請原諒我的藉口,但我沒有明白爲什麼你使用max()函數? – user1046403

+0

@ user1046403。 。 。將兩個值放入同一行。 –

相關問題