MariaDB – 喜欢子句

MariaDB – 喜欢子句


WHERE 子句提供了一种在操作使用精确匹配时检索数据的方法。在需要具有共享特征的多个结果的情况下,LIKE子句适用于广泛的模式匹配。

LIKE 子句测试模式匹配,返回真或假。用于比较的模式接受以下通配符:“%”,匹配字符数(0 或更多);和“_”,匹配单个字符。“_”通配符仅匹配其集合中的字符,这意味着在使用另一个集合时将忽略拉丁字符。默认情况下,匹配项不区分大小写,需要额外设置区分大小写。

NOT LIKE 子句允许测试相反的条件,很像not运算符。

如果语句表达式或模式的计算结果为 NULL,则结果为 NULL。

查看下面给出的一般 LIKE 子句语法 –

SELECT field, field2,... FROM table_name, table_name2,...
WHERE field LIKE condition

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

命令提示符

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

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

PHP 脚本使用 Like 子句

使用的mysql_query()函数中使用LIKE子句声明

<?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 LIKE "xyz%"';
   
   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

觉得文章有用?

点个广告表达一下你的爱意吧 !😁