我在Mysql中使用php,当用户在date_field中选择月份和年份时,我需要运行特定的查询。此查询返回由用户选择的月/年创建的所有记录,我不希望在选择中的子句中关联天数。由于我只需要选择月/年的记录,有什么方法可以在仅选择月/年中定义?
这是我的Mysql语句,其中变量由用户选择有两个与内部连接相关的表,因此我可以使用 Date "抓取"记录:
$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";
谁能帮我?
这很容易。使用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";
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 年份,两位数
我将月份年份转换为 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";