简体   繁体   中英

mysql select from a table depending on in which table the data is in

I have 3 tables holding products for a restaurant. Products that reside in the bar, food and ingredients.

I use php and mysql. I have another table that holds information about the orders that have been made so far. There are 2 fields, the most important ones, that hold information about the id of the product and the type (from the bar, from the kitchen or from the ingredients). I was thinking to write the sql query like below to use either the table for bar products, kitchen or ingredients but it doesn't work. Basically the second table on join must be either "bar", "produse" or "stoc".

SELECT K.nume, 
       COUNT(K.cantitate) as cantitate, 
       SUM(K.pret) as pret, 
       P.nume as NumeProduse 
  FROM `clienti_fideli` as K 
  JOIN if(K.tip,bar,produse) AS P ON K.produs = P.id_prod 
 WHERE K.masa=18 and K.nume LIKE 'livrari-la-domiciliu' 
GROUP BY NumeProduse

I don't think you can do that.

can you change the database schema? a better option would be to have bar, food and ingredients in a single table (eg product) with a field type which would be either 'bar', 'produse' or 'stoc'

SELECT K.nume, 
       COUNT(K.cantitate) as cantitate, 
       SUM(K.pret) as pret, 
       P.nume as NumeProduse 
  FROM `clienti_fideli` as K 
  JOIN product AS P ON K.produs = P.id_prod  AND P.tip = <product_type>
 WHERE K.masa=18 and K.nume LIKE 'livrari-la-domiciliu' 
GROUP BY NumeProduse

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