我希望获得特定类别的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_name
与item_sold
匹配$current_month
答案 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