在两个日期之间过滤MySQL结果

时间:2012-02-29 09:32:58

标签: mysql group-by left-join inner-join where-clause

我使用以下查询来获取我演示的结果

SELECT 
b.sales_title,c.cat_name,COUNT(b.sales_id) as cnt,COUNT(DISTINCT e.comment_id) as coun
FROM tb_sale_report a 
INNER JOIN tbl_sales b on a.sales_id=b.sales_id 
INNER JOIN tb_category c on c.cat_id=b.category_id 
LEFT JOIN tb_comment e on b.sales_id=e.sales_id 
GROUP BY b.sales_title

 +------------+---------+--------+------+
| sales_title | cat_name| cnt    | coun |
+-------------+---------+--------+------+
| My Sales    |Toys     |20      |5     |
| First Sale  |Dress    |28      |1     |
|Premium      |Computer |7       |16    |
+-------------+--------+---------+------+

现在在表tb_sale_report中我还有另一个名为view_date的字段,它将存储记录ID添加的日期。现在我打算在表tb_search_report中添加一个过滤选项,用户可以在其中搜索特定日期(例如开始日期和结束日期)之间添加的记录。如何编写where条件以按指定的日期过滤结果。 需要帮助。谢谢。

3 个答案:

答案 0 :(得分:2)

尝试以下:

SELECT 
b.sales_title,c.cat_name,COUNT(b.sales_id) as cnt,COUNT(DISTINCT e.comment_id) as coun
FROM tb_sale_report a 
INNER JOIN tbl_sales b on a.sales_id=b.sales_id 
INNER JOIN tb_category c on c.cat_id=b.category_id 
LEFT JOIN tb_comment e on b.sales_id=e.sales_id 
where left(a.view_date,10) between 'start_date' and 'end_date';
GROUP BY b.sales_title

请将start_date和end_date替换为值

答案 1 :(得分:1)

尝试并执行此查询

SELECT 
b.sales_title,c.cat_name,COUNT(b.sales_id) as cnt,COUNT(DISTINCT e.comment_id) as coun
FROM tb_sale_report a 
INNER JOIN tbl_sales b on a.sales_id=b.sales_id 
INNER JOIN tb_category c on c.cat_id=b.category_id 
LEFT JOIN tb_comment e on b.sales_id=e.sales_id 
WHERE b.sales_date BETWEEN $start_date AND $end_date 
GROUP BY b.sales_title

答案 2 :(得分:0)

最简单的解决方案是添加带有BETWEEN sunclause的WHERE子句,例如

WHERE view_date BETWEEN date1 AND date2