获取特定月份的类别的畅销书

时间:2015-03-29 23:32:48

标签: sql mysqli

我希望获得特定类别的3个最畅销商品(如果当然有任何已售商品)。

我跑的时候

SELECT  io.item_name,  
    COUNT(io.item_name) AS number_sold  
FROM  category_tbl AS c   
    LEFT JOIN item_out_tbl AS io ON io.category_id = c.category_id
        AND c.category_id = '$category_id'
    LEFT JOIN sales_tbl    AS sa ON io.item_id = sa.item_id                               
        AND '$current_month'=MONTH(date_sold) 
GROUP BY  io.item_name 
ORDER BY number_sold DESC 
LIMIT 3

即使那些MONTH(date_sold)不等于$current_month,我也会得到结果,'$current_month'=MONTH(date_sold)被忽略。我希望结果为空,因为我没有item_nameitem_sold匹配$current_month

2 个答案:

答案 0 :(得分:2)

您的left join似乎没必要。解决问题的更好方法就是使用内部联接:

SELECT  io.item_name, COUNT(io.item_name) AS number_sold  
FROM item_out_tbl io JOIN
     category_tbl c   
     ON io.category_id = c.category_id AND c.category_id = '$category_id' JOIN
     sales_tbl sa
     ON io.item_id = sa.item_id AND                            
        $current_month' = MONTH(date_sold) 
GROUP BY io.item_name 
ORDER BY number_sold DESC 
LIMIT 3

答案 1 :(得分:0)

当您使用left join时,如果等效值不存在,则从连接表中获取空值,因此只需添加WHERE sa.item_id IS NOT NULL子句:

SELECT  io.item_name,  
    COUNT(io.item_name) AS number_sold  
FROM  category_tbl AS c   
    LEFT JOIN item_out_tbl AS io ON io.category_id = c.category_id
        AND c.category_id = '$category_id'
    LEFT JOIN sales_tbl    AS sa ON io.item_id = sa.item_id                               
        AND '$current_month'=MONTH(date_sold) 
WHERE sa.item_id IS NOT NULL
GROUP BY  io.item_name 
ORDER BY number_sold DESC 
LIMIT 3