「SQLコーディングスタイル」の版間の差分

提供:MoodleDocs
移動先:案内検索
8行目: 8行目:
* パラメータプレースホルダを使用してください!
* パラメータプレースホルダを使用してください!
* すべてのSQLキーワードは大文字にしてください。
* すべてのSQLキーワードは大文字にしてください。
* All SQL queries and fragments should be enclosed in double quotes.
* すべてのSQLクエリおよびフラグメントは二重引用符で囲んでください。
* すべてのSQLクエリおよびフラグメントは二重引用符で囲んでください。All SQL queries and fragments should be enclosed in double quotes.
* Complex SQL queries should be on multiple lines.
* Complex SQL queries should be on multiple lines.
* 複雑なSQLクエリは複数行に記述してください。Complex SQL queries should be on multiple lines.
* Multiline SQL queries should be right aligned on SELECT, FROM, JOIN, WHERE, GROUPY BY and HAVING.
* Multiline SQL queries should be right aligned on SELECT, FROM, JOIN, WHERE, GROUPY BY and HAVING.
* Use JOIN instead of INNER JOIN.
* Use JOIN instead of INNER JOIN.

2021年2月4日 (木) 15:01時点における版

作成中です - Mitsuhiro Yoshida (トーク)

このページでは複雑なデータベースクエリに関する推奨コーディングスタイルを説明します。

完全なSQLクエリは$DB->get_records_sql()、$DB->get_recordset_sql()または$DB->execute()で使用されます。SQLフラグメントは接尾辞「_select()」を使ったDMLメソッドに使用できます。

一般規則 General rules

  • パラメータプレースホルダを使用してください!
  • すべてのSQLキーワードは大文字にしてください。
  • すべてのSQLクエリおよびフラグメントは二重引用符で囲んでください。
  • Complex SQL queries should be on multiple lines.
  • 複雑なSQLクエリは複数行に記述してください。Complex SQL queries should be on multiple lines.
  • Multiline SQL queries should be right aligned on SELECT, FROM, JOIN, WHERE, GROUPY BY and HAVING.
  • Use JOIN instead of INNER JOIN.
  • Do not use right joins.
  • Always use AS keyword for column aliases.
  • Never use AS keyword for table aliases.
  • Use <> for comparing if values are not equals and do not use !=

二重引用符 Double quotes

All sql queries and fragments should be enclosed in double quotes, do not concat SQL from multiple parts if possible. The single quotes are used for sql strings, it also helps with visual highlighting and SQL code completion in some IDEs.

$records = $DB->get_records_select('some_table', "id > ?", array(111));

パラメータプレースホルダ Parameter placeholders

All variable query parameters must be specified via placeholders. It is possible to use three different types of placeholders: :named, ? and $1. It is recommended to use named parameters if there is more than one parameter.

$sql = "SELECT *

         FROM {some_table}
        WHERE id > :above";

$records = $DB->get_records_sql($sql, array('above'=>111));

インデント Indentation

sql indentation.png

サブクエリ Subqueries

There are no strict rules for subquery indentation, the deciding factor is good readability - see MDLSITE-1914.

関連情報