简体   繁体   中英

Need MySQL query from three tables

I have three tables:

Items:
Id   |Name   | Price    | Cat_Id 
---- |-------|----------------
 1   | Item1 |   50.00  | 1    
 2   | Item2 |   25.20  | 5

Category:  
Id   |Name  | 
---- |------|
 1   | Cat1 |    
 2   | Cat2 |

Discount:  
Id   |Item_Id| Client_Id|Discount 
---- |-------|----------------
 1   |   1   |   1      | 10    
 2   |   1   |   2      | 15
 3   |   2   |   2      | 6

I am trying to get all items with proper discount, which is different for every customer. In this example i have client with Client_Id 1, which have discount for Item1/10/ and he doesn`t have discount on Item2. The result should look like this:

Id   |Name   | Price    | Cat | Discount
---- |-------|----------------|----------
 1   | Item1 |   50.00  | Cat1|   10
 2   | Item2 |   25.20  | Cat5|   0

My question is what is the way to build the query. I join first two tables and need to filter the third, but should I use temp table or do query in query?

It's Simple SQL Query.

Select Id, Name, Price, Cat, Discount From Items
left join discount on Items.id=discount.Item_Id 
left join category on Items.cat_id=id

Output Like:

Id   |Name   | Price    | Cat | Discount
---- |-------|----------------|----------
 1   | Item1 |   50.00  | Cat1|   10
 2   | Item2 |   25.20  | Cat5|   0

Try this way:

select di.id,di.Client_Id,it.Name,it.Price,ca.Cat,ifnull(di.Discount,0)
from Discount di
    right join Items it on di.Item_id=it.Id
    left join Category ca on it.Cat_Id=ca.Id
order by di_Id,di.Client_id,It.Name       

You get all rows from discount and then get all items and look for the category. If an item has no discount(null) you get a 0

To get the result you want,

following is the query...

select
     i.id item_id,
     d.id discount_id,
     i.name,
     i.price,
     c.name cat_name,
     d.discount
from items i
left join discount d on i.id = d.item_id
left join category c on i.cat_id = c.id
where d.client_id = 1 or d.client_id is null;
/*where condition added after update as OP required*/

UPDATE

As per OP's comment

select
    i.id item_id,d.id discount_id,
    i.name,i.price,c.name cat_name,d.discount
from discount d
left join items i on i.id = d.item_id
left join category c on i.cat_id = c.id
where d.client_id = 2;

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