我使用php和Mysql,当用户在date_field中选择月份和年份时,我需要运行特定的查询。 此查询返回由用户选择的月/年创建的所有记录,并且我不希望在select中的子句中关联日期。 由于我只需要从月/年选择的记录,有什么方法可以在仅选择月/年内定义?
这是我的Mysql语句,其中包含用户选择的变量 有两个与内部联接相关的表格,因此我可以“抓住”#39;记录日期:
$quer_mesano = "Select b.name AS Canal
from canal_canalvenda b
inner join meta_meta c On c.canal_canalvenda_id_c = b.id
And c.deleted = 0
where c.periodo = '$month_year' //Here is the date value I just need to put in month/year
And b.deleted = 0
Group by Canal order by 1";
任何人都可以帮助我吗?
答案 0 :(得分:3)
这很容易。使用DATE_FORMAT。只需像这样更改Sql语句:
$quer_mesano = "Select b.name AS Canal
from canal_canalvenda b
inner join meta_meta c On c.canal_canalvenda_id_c = b.id
And c.deleted = 0
where DATE_FORMAT( c.periodo, '%Y-%m' ) = '$month_year' //Just put DATE_FORMAT
And b.deleted = 0
Group by Canal order by 1";
答案 1 :(得分:2)
DATE_FORMAT()您可以使用如下所示
$quer_mesano = "Select b.name AS Canal
from canal_canalvenda b
inner join meta_meta c On c.canal_canalvenda_id_c = b.id
And c.deleted = 0
where DATE_FORMAT( c.periodo, '%Y/%m' ) = '$month_year'
And b.deleted = 0
Group by Canal order by 1";
一个月你有不同的类型 - %M月份名称 %m月,数字(00-12) 一年 - %Y年,四位数 %y年,两位数
答案 2 :(得分:1)
我将月份年份转换为YYYY-MM格式,可以将其与数据库进行比较。
$quer_mesano = "Select b.name AS Canal
from canal_canalvenda b
inner join meta_meta c On c.canal_canalvenda_id_c = b.id
And c.deleted = 0
where DATE_FORMAT( c.periodo, '%Y-%m' ) = '" . date("Y-m", strtotime($month_year)) . "' //Here is the date value I just need to put in month/year
And b.deleted = 0
Group by Canal order by 1";