简体   繁体   中英

mysql select from one or another table

Thanks, for your help, I posted a simplified version of my problem but I really didn't understand how to apply the left join in the big one that is this:

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

The problem is that when d.type='I' I need the items from table a, but if d.type='S' I need the items from table B, the prices are on table c.

Thank you very much.

If you need something like this, that's clearly indicates that your database structure is wrong.
It should be one table, and your query become plain and easy.

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

Things to learn:


I have an rawFood table, a cookedFood table and a Menu table and the menu table has things from both, rawFood and cookedFood, thats why I need to join that way

You need to have a single food table, and give it a column that notes the difference between raw and cooked food.

You can use a left join

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM