2010-08-19 19 views
2

謝謝您的幫助,我貼我的問題的一個簡化版本,但我真的不明白如何運用左側的大單是這個連接:MySQL的一個或另一個表選擇

SELECT d.type, 
     d.item , 
     if(d.type='I', a.name, b.name) as name, 
     if(d.type='I', c.price,0) as price, 
     if(d.type='I',if(d.taxes='yes', 
     (c.priceWithTax*d.weight), (c.price*d.weight)),0) as totalprice 
    FROM d 
inner join a on d.item=a.id 
inner join c on d.item=c.item 
    where c.sede =1 

問題是,當d.type ='我'需要表a中的項目,但是如果d.type ='S'我需要表B中的項目,價格在表c中。

非常感謝。

+2

能否請你讓你的問題更清楚了嗎?也許真實世界的例子可能有所幫助? – 2010-08-19 20:33:21

+0

我相信他問他如何才能加入桌子C只有當b.col2 = apple – 2010-08-19 20:35:57

回答

0
select 
    a.col1, 
    b.col1, 
    coalesce(c.col1,0) 
from a inner join b on a.col0=b.col1 
    left outer join c on b.col2='apple' and c.col1=b.col0 

東西要學:


我有一個rawFood表,cookedFood表和菜單表和菜單表有來自兩件事,rawFood和cookedFood,這就是爲什麼我要加入這樣

你需要有一個單一的food表,並給它一列,記錄生食和熟食的區別。

+0

感謝您的幫助,我發佈了我的問題的簡化版本,但是我真的不知道如何在這個大應用中加入左連接: SELECT如果(d.type ='I',a.name,b.name)作爲名稱,if(d.type ='I',c.price,0)作爲價格,if(d.type,d.item, d.type ='I',if(d.taxes ='yes',(c.priceWithTax * d.weight),(c.price * d.weight)),0)as totalprice FROM d inner join a on d .item = a.id inner join c on d.item = c.item其中c.sede = 1 問題是,當d.type ='我'需要表a中的項目,但如果d.type ='S'我需要表B中的物品,價格在表c中。 非常感謝。 – notforever 2010-08-19 22:42:57

0

如果你需要這樣的東西,這很清楚地表明你的數據庫結構是錯誤的。
它應該是一個表,並且您的查詢變得簡單和容易。

+0

謝謝你的答案Col Shrapnel,問題是我有一個rawFood桌子,一個熟食桌子,一個Menu桌子和菜單表從rawFood和cookedFood都有東西,這就是爲什麼我需要以這種方式加入 – notforever 2010-08-19 20:53:41

+0

@notforever,但它必須是一張桌子,並且有一個名爲「raw」(或「cooked」)的字段 - 無論如何。這是非常基本的數據庫規則。所有類似的數據應該在一個表格中。或者你會不斷遇到這樣的問題 – 2010-08-20 06:07:58

0

您可以使用左連接

select 
    a.col1, 
    b.col1, 
    ifnull(c.col1,0) 
from a 
    inner join b on a.col0=b.col1 
    left join c on (c.col1 = b.col0 and b.col2="apple") 
where 
    b.col2 != "apple" or (b.col2 = "apple" and c.col1 is not null) 
+0

感謝您的幫助,我發佈了一個我的問題的簡化版本,但我真的不知道如何在這個大的應用左連接: SELECT d.type,d.item,if(d (d.type ='I',c.price,0)as price,if(d.type ='I',if(d .type ='I',a.name,b.name)as name,if .taxes ='yes',(c.priceWithTax * d.weight),(c.price * d.weight)),0)as totalprice FROM d inner join a on d.item = a。id內連接C上d.item = c.item其中c.sede = 1 問題是,當d.type ='我'我需要從表a的項目,但如果d.type ='S'我需要表B中的物品,價格在表c中。 非常感謝。 – notforever 2010-08-19 22:49:58

相關問題