我们可以在where子句中仅使用日期的月份和年份部分来过滤日期字段吗?
SELECT `outlet`.`outlet`,cities.`city`,teritory.`teritory`,region.`region`,`countries`.`country` FROM `audit`
JOIN `user` ON `user`.`id`=`audit`.`auditor_id`
JOIN `user_outlet` ON `user_outlet`.id=`audit`.`outlet_id`
JOIN `outlet` ON `outlet`.id=`user_outlet`.`outlet_id`
JOIN `cities` ON `cities`.`id`=`outlet`.`city_id`
JOIN `teritory_city` ON `teritory_city`.`city_id`=`cities`.id
JOIN `teritory` ON `teritory_city`.`teritory_id`=`teritory`.`id`
JOIN `region` ON `region`.`id`=`teritory`.`region_id`
JOIN `org_country` ON `org_country`.`id`=`region`.`org_country_id`
JOIN `countries` ON `countries`.`id`=`org_country`.`country_id`
WHERE `audit`.`created_date`=?
上面是我尝试过的查询,我必须传递年和月参数而不是传递日期。 在UI中,Year和months是我提供给用户的唯一过滤器,以获取该特定月份和年份中的相应数据。
答案 0 :(得分:1)
像下面一样使用year()
和month()
函数-
SELECT `outlet`.`outlet`,cities.`city`,teritory.`teritory`,region.`region`,`countries`.`country` FROM `audit`
JOIN `user` ON `user`.`id`=`audit`.`auditor_id`
JOIN `user_outlet` ON `user_outlet`.id=`audit`.`outlet_id`
JOIN `outlet` ON `outlet`.id=`user_outlet`.`outlet_id`
JOIN `cities` ON `cities`.`id`=`outlet`.`city_id`
JOIN `teritory_city` ON `teritory_city`.`city_id`=`cities`.id
JOIN `teritory` ON `teritory_city`.`teritory_id`=`teritory`.`id`
JOIN `region` ON `region`.`id`=`teritory`.`region_id`
JOIN `org_country` ON `org_country`.`id`=`region`.`org_country_id`
JOIN `countries` ON `countries`.`id`=`org_country`.`country_id`
WHERE year(`audit`.`created_date`)=yearparam and month(`audit`.`created_date`)=monthparam
答案 1 :(得分:0)
尝试避免在WHERE
子句的列上使用函数。这可能会阻止优化器选择最佳的优化计划。
我建议:
where audit.created_date >= date(concat_ws('-', @yearparam, @monthparam, 1) and
audit.created_date < date(concat_ws('-', @yearparam, @monthparam, 1) + interval 1 month