Mariadb 简明教程

MariaDB - Where Clause

WHERE 子句过滤各种语句,例如 SELECT、UPDATE、DELETE 和 INSERT。它们提供了用于指定动作的条件。它们通常出现在语句中的表名之后,其条件随之而来。WHERE 子句本质上就像一个 if 语句。

查看下面给出的 WHERE 子句的一般语法 −

[COMMAND] field,field2,... FROM table_name,table_name2,... WHERE [CONDITION]

注意 WHERE 子句的以下特性 −

  1. It is optional.

  2. 它允许指定任何条件。

  3. 它允许通过 AND 或 OR 操作符指定多个条件。

  4. 大小写敏感性仅适用于使用 LIKE 比较的语句。

WHERE 子句允许使用以下运算符 −

Operator

= !=

> <

>= ⇐

WHERE 子句可以在命令提示符或 PHP 脚本中使用。

The Command Prompt

在命令提示符下,只需使用标准命令 −

root@host# mysql -u root -p password;
Enter password:*******
mysql> use PRODUCTS;
Database changed
mysql> SELECT * from products_tbl WHERE product_manufacturer = 'XYZ Corp';
+-------------+----------------+----------------------+
| ID_number   | Nomenclature   | product_manufacturer |
+-------------+----------------+----------------------+
| 12345       | Orbitron 4000  | XYZ Corp             |
+-------------+----------------+----------------------+
| 12346       | Orbitron 3000  | XYZ Corp             |
+-------------+----------------+----------------------+
| 12347       | Orbitron 1000  | XYZ Corp             |
+-------------+----------------+----------------------+

使用 AND 条件查看示例 −

SELECT *
FROM products_tbl
WHERE product_name = 'Bun Janshu 3000';
AND product_id <= 344;

此示例结合 AND 和 OR 条件

SELECT *
FROM products_tbl
WHERE (product_name = 'Bun Janshu 3000' AND product_id < 344)
OR (product_name = 'Bun Janshu 3000');

PHP Scripts Using Where Clause

在使用 WHERE 子句的操作中使用 mysql_query() 函数 −

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql = 'SELECT product_id, product_name, product_manufacturer, ship_date
      FROM products_tbl
      WHERE product_manufacturer = "XYZ Corp"';

   mysql_select_db('PRODUCTS');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Product ID :{$row['product_id']} <br> ".
         "Name: {$row['product_name']} <br> ".
         "Manufacturer: {$row['product_manufacturer']} <br> ".
         "Ship Date: {$row['ship_date']} <br> ".
         "--------------------------------<br>";
   }

   echo "Fetched data successfully\n";
   mysql_close($conn);
?>

当数据检索成功时,您将看到以下输出 −

Product ID: 12345
Nomenclature: Orbitron 4000
Manufacturer: XYZ Corp
Ship Date: 01/01/17
----------------------------------------------
Product ID: 12346
Nomenclature: Orbitron 3000
Manufacturer: XYZ Corp
Ship Date: 01/02/17
----------------------------------------------
Product ID: 12347
Nomenclature: Orbitron 1000
Manufacturer: XYZ Corp
Ship Date: 01/02/17
----------------------------------------------
mysql> Fetched data successfully