mysql从一个或另一个表中选择

时间:2010-08-19 20:29:45

标签: mysql if-statement

谢谢,在你的帮助下,我发布了我的问题的简化版本但我真的不明白如何将左连接应用于这个大的那个:

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上。

非常感谢。

3 个答案:

答案 0 :(得分:0)

如果你需要这样的东西,那就清楚地表明你的数据库结构是错误的 它应该是一个表,您的查询变得简单明了。

答案 1 :(得分: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表和一个Menu表,菜单表中包含了rawFood和cookedFood的东西,这就是为什么我需要以这种方式加入

你需要一个food表,并给它一个列,记录生食和熟食的区别。

答案 2 :(得分: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)
相关问题