0
0

More than 1 year has passed since last update.

【SQL】PHPで範囲検索のSQL文をシンプルに書く方法

Last updated at Posted at 2022-10-12

範囲検索のSQL文をどう書く?

このような日付の範囲検索画面を作る場合のSQL文について学習したので記録しておきます。

記述例1

test.php

$SQL= "";
$SQL .=" select * ";
$SQL .=" from URIAGE_T";
$SQL .=" where (CD = 1200)";

	//条件:売上日
	if((!empty($Inq_DATE_F))and(!empty($Inq_DATE_T))){
		$SQL .=" and (URIDATE between '".$Inq_DATE_F."'and'".$Inq_DATE_T."')";
	}elseif((!empty($Inq_DATE_F))and(empty($Inq_DATE_T))){
		$SQL .=" and (URIDATE >= '".$Inq_DATE_F."')";
	}elseif((empty($Inq_DATE_F))and(!empty($Inq_DATE_T))){
		$SQL .=" and (URIDATE <= '".$Inq_DATE_T."')";
	}else{
		//何も行わない
	}

記述例2

test.php

$SQL= "";
$SQL .=" select * ";
$SQL .=" from URIAGE_T";
$SQL .=" where (CD = 1200)";

	//条件:売上日
	if ($Inq_DATE_F != ""){
		$SQL .=" and (URIDATE >= '".$Inq_DATE_F."')";
	}
	if ($Inq_DATE_T != ""){
		$SQL .=" and (URIDATE <= '".$Inq_DATE_T."')";
	}

記述例2の方がシンプルでGood。

記述例1でも検索には問題ないが、「between」を使用している。
betweenは、桁数が可変だと抽出は機能しないので、使用する場合には注意が必要。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0