Mysql-where-clause
MySQL-WHERE句
MySQLテーブルからデータを取得するSQL SELECT コマンドを見てきました。 WHERE Clause と呼ばれる条件句を使用して、結果を除外できます。 このWHERE句を使用して、選択条件を指定して、テーブルから必要なレコードを選択できます。
構文
次のコードブロックには、MySQLテーブルからデータを取得するためのWHERE句を含むSELECTコマンドの一般的なSQL構文があります-
コンマで区切られた1つ以上のテーブルを使用して、WHERE句を使用してさまざまな条件を含めることができますが、WHERE句はSELECTコマンドのオプション部分です。
WHERE句を使用して、任意の条件を指定できます。
AND または OR 演算子を使用して、複数の条件を指定できます。
WHERE句をDELETEまたはUPDATE SQLコマンドとともに使用して、条件を指定することもできます。
以下に、 WHERE 句で使用できる演算子のリストを示します。
フィールドAが10を保持し、フィールドBが20を保持すると仮定します-
Operator | Description | Example |
---|---|---|
= | Checks if the values of the two operands are equal or not, if yes, then the condition becomes true. | (A = B) is not true. |
!= | Checks if the values of the two operands are equal or not, if the values are not equal then the condition becomes true. | (A != B) is true. |
> | Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true. | (A > B) is not true. |
< | Checks if the value of the left operand is less than the value of the right operand, if yes then the condition becomes true. | (A < B) is true. |
>= | Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true. | (A >= B) is not true. |
⇐ | Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true. | (A ⇐ B) is true. |
WHERE句は、特に MySQL Join を使用する場合に、テーブルから選択した行をフェッチする場合に非常に役立ちます。 結合については、別の章で説明します。
指定された条件がテーブル内のどのレコードとも一致しない場合、クエリは行を返しません。
コマンドプロンプトからのデータの取得
これは、SQL SELECTコマンドとWHERE句を使用して、選択したデータをMySQLテーブル( tutorials_tbl )からフェッチします。
例
次の例では、作成者名が Sanjay である tutorials_tbl テーブルからすべてのレコードを返します。
文字列で LIKE 比較を実行しない限り、比較では大文字と小文字が区別されません。 次のように BINARY キーワードを使用して、検索で大文字と小文字を区別できます-
PHPスクリプトを使用したデータの取得
PHP関数* mysql_query()のWHERE CLAUSEで同じSQL SELECTコマンドを使用できます。 この関数は、SQLコマンドの実行に使用され、後で別のPHP関数 mysql_fetch_array()*を使用して、選択したすべてのデータをフェッチできます。 この関数は、連想配列、数値配列、またはその両方として行を返します。 行がもうない場合、この関数はFALSEを返します。
例
次の例は、著者名が Sanjay である tutorials_tbl テーブルからすべてのレコードを返します-