教程 > mysql 教程 > 阅读:42

mysql like 子句——迹忆客-ag捕鱼王app官网

我们知道在 mysql 中使用 sql select 命令来读取数据, 同时我们可以在 select 语句中使用 where 子句来获取指定的记录。

where 子句中可以使用等号 = 来设定获取数据的条件,如 "jiyik_author = 'fql'"。

但是有时候我们需要获取 jiyik_author 字段含有 "com" 字符的所有记录,这时我们就需要在 where 子句中使用 sql like 子句。

sql like 子句中使用百分号 %字符来表示任意字符,类似于unix或正则表达式中的星号 *。

如果没有使用百分号 %, like 子句与等号 = 的效果是一样的。

语法

以下是 sql select 语句使用 like 子句从数据表中读取数据的通用语法:

select field1, field2,...fieldn 
from table_name
where field1 like condition1 [and [or]] filed2 = 'somevalue'
  • 你可以在 where 子句中指定任何条件。
  • 你可以在 where 子句中使用like子句。
  • 你可以使用like子句代替等号 =。
  • like 通常与 % 一同使用,类似于一个元字符的搜索。
  • 你可以使用 and 或者 or 指定一个或多个条件。
  • 你可以在 delete 或 update 命令中使用 where...like 子句来指定条件。

在命令提示符中使用 like 子句

以下我们将在 sql select 命令中使用 where...like 子句来从mysql数据表 jiyik_tbl 中读取数据。

示例

以下是我们将 jiyik_tbl 表中获取 jiyik_author 字段中以 com 为结尾的的所有记录:

sql like 语句:

mysql> use jiyik;
database changed
mysql> select * from jiyik_tbl  where jiyik_author like '%com';
 ---------- ---------------- -------------- ----------------- 
| jiyik_id | jiyik_title    | jiyik_author | submission_date |
 ---------- ---------------- -------------- ----------------- 
|        5 | python3 教程   | jiyik.com    | 2021-03-08      |
|        6 | redis 教程     | onmpw.com    | 2021-03-08      |
 ---------- ---------------- -------------- ----------------- 
2 rows in set (0.00 sec)

在php脚本中使用 like 子句

你可以使用php的 mysqli query()或mysql_query()函数及相同的 sql select 带上 where...like 子句的命令来获取数据。

该函数用于执行 sql 命令,然后通过 php 函数 mysqli_fetch_array() 来输出所有查询的数据。

但是如果是 delete 或者 update 中使用 where...like 子句的s ql 语句,则无需使用 mysqli_fetch_array() 函数。

语法

$mysqli->query($sql,$resultmode)
参数 描述
$sql 必需。规定要使用的 mysql 连接。
resultmode 可选。一个常量。可以是下列值中的任意一个:
mysqli_use_result(如果需要检索大量数据,请使用这个)
mysqli_store_result(默认)

示例

以下是我们使用php脚本在 jiyik_tbl 表中读取 jiyik_author 字段中以 com 为结尾的的所有记录:

connect_errno ) {
    printf("connect failed: %s\n", $mysqli->connect_error);
    exit();
}
printf("connected successfully.\n");
$sql = 'select jiyik_id, jiyik_title, jiyik_author, submission_date 
            from jiyik_tbl where jiyik_author like "%com"';
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        printf("id: %s, title: %s, author: %s, date: %d \n",
            $row["jiyik_id"],
            $row["jiyik_title"],
            $row["jiyik_author"],
            $row["submission_date"]);
    }
} else {
    printf("no record found.\n");
}
mysqli_free_result($result);
$mysqli->close();
?>

结果如下:

connected successfully.
id: 5, title: python3 教程, author: jiyik.com, date: 2021 
id: 6, title: redis 教程, author: onmpw.com, date: 2021 

查看笔记

扫码一下
查看教程更方便
网站地图