1. Go to this page and download the library: Download haikara/sequel-builder library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// item_codeが00001で、deleted_flagがNULLではないレコードを抽出
$builder = SQL::select('items')
->where(fn (Rules $rules) => $rules
->equals('item_code', '00001')
->isNotNull('deleted_flag'));
/*
SELECT items.*
FROM items
WHERE
item_code = ?
AND deleted_flag IS NOT NULL
*/
/* equalsの第二引数に、テーブル名.カラム名の文字列をそのまま渡すと、エスケープされてしまい、
テーブル名.カラム名として扱われなくなってしまうので、Rawクラスを渡す必要がある。 */
$builder = SQL::select('items')
->columns('items.id', 'items.item_code', 'items.item_name', 'categories.category_name')
->leftJoin('categories', fn (Rules $rules) => $rules
->equals('categories.id', new Raw('items.category_id')))
/*
SELECT
items.id, items.item_code, items.item_name, categories.category_name
FROM items
LEFT JOIN categories
ON categories.id = items.category_id
*/
// 取引先ごとの月間売上テーブルを検索。年間の売上が1000000以上の取引先、という条件で絞り込む。
// customer_code = 取引先コード、amount = 売上金額とする。
$builder = SQL::select('monthly_sales')
->columns('customer_code', 'SUM(amount) AS yearly_sales')
->groupBy('customer_code')
->having(fn (Rules $rules) => $rules
->compare('yearly_sales', '>=', 1000000));
/*
SELECT
customer_code, SUM(amount) AS yearly_sales
FROM monthly_sales
GROUP BY customer_code
HAVING
yearly_sales >= 1000000
*/
// 月間売上テーブルを集計し、年間売上の多い順に取得
$builder = SQL::select('monthly_sales')
->columns('customer_code', 'SUM(amount) AS yearly_sales')
->groupBy('customer_code')
->orderByDesc('yearly_sales');
/*
SELECT
customer_code, SUM(amount) AS yearly_sales
FROM monthly_sales
GROUP BY customer_code
ORDER BY yearly_sales DESC
*/
// category_idが1か2の商品情報を取得する
$builder = SQL::select('items')
->where(fn (Rules $rules) => $rules
->isNotNull('deleted_flag')
->any(fn (Rules $rules) => $rules
->equals('category_id', 1)
->equals('category_id', 2)));
/*
SELECT items.*
FROM items
WHERE
deleted_flag IS NOT NULL
AND (
category_id = ?
OR category_id = ?
)
*/
$builder = SQL::select('items')
->where(fn (Rules $rules) => $rules
->isNotNull('deleted_flag')
->in('category_id', [1, 2]));
/*
SELECT items.*
FROM items
WHERE
deleted_flag IS NOT NULL
AND category_id IN (?, ?)
*/
// 何らかの申請情報を持つrequestsテーブルと、承認された申請のidを保持するapproved_requestsテーブルを想定。
// サブクエリを用いて、承認済みの申請の情報のみを取得する。
$builder = SQL::select('requests')
->where(fn (Rules $rules) => $rules
->in('id', SQL::select('approved_requests')->columns('request_id')));
/*
SELECT requests.*
FROM requests
WHERE
id IN (SELECT request_id FROM approved_requests)
*/
$builder = SQL::select('categories')
->columns(
'id',
'category_name',
SQL::raw("CASE WHEN id = ? THEN 'selected' ELSE '' END AS selected")
->bindValue($post['category_id']) // 値をバインド
);