2010-08-19 43 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

相关问题