在 MySQL 中查找列值以特定子字符串结尾的行?
mysqlmysqli database
要查找行并使用新值进行更新,其中列值以特定子字符串结尾,您需要使用 LIKE 运算符。
语法如下:
UPDATE yourTableName SET yourColumnName=’yourValue’ WHERE yourColumnName LIKE ‘%.yourString’;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table RowEndsWithSpecificString -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FileName varchar(30), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.50 sec)
现在您可以使用 insert 命令在表中插入一些记录。查询如下:
mysql> insert into RowEndsWithSpecificString(FileName) values('MergeSort.c'); Query OK, 1 row affected (0.11 sec) mysql> insert into RowEndsWithSpecificString(FileName) values('BubbleSortIntroduction.pdf'); Query OK, 1 row affected (0.25 sec) mysql> insert into RowEndsWithSpecificString(FileName) values('AllMySQLQuery.docx'); Query OK, 1 row affected (0.18 sec) mysql> insert into RowEndsWithSpecificString(FileName) values('JavaCollections.pdf'); Query OK, 1 row affected (0.16 sec) mysql> insert into RowEndsWithSpecificString(FileName) values('JavaServlet.pdf'); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录。查询如下:
mysql> select *from RowEndsWithSpecificString;
输出结果如下:
+----+----------------------------+ | Id | FileName | +----+----------------------------+ | 1 | MergeSort.c | | 2 | BubbleSortIntroduction.pdf | | 3 | AllMySQLQuery.docx | | 4 | JavaCollections.pdf | | 5 | JavaServlet.pdf | +----+----------------------------+ 5 rows in set (0.00 sec)
以下查询用于查找并更新列值以特定子字符串结尾的位置。以下查询查找以".docx"结尾的子字符串并使用新的子字符串".pdf"进行更新。查询如下:
mysql> update RowEndsWithSpecificString -> set FileName='IntroductionToCoreJava.pdf' -> where FileName LIKE '%.docx'; Query OK, 1 row affected (0.14 sec) Rows matched: 1 Changed: 1 Warnings: 0
现在再次检查表记录。查询如下:
mysql> select *from RowEndsWithSpecificString;
输出结果如下:
+----+----------------------------+ | Id | FileName | +----+----------------------------+ | 1 | IntroductionToCoreJava.pdf | | 2 | BubbleSortIntroduction.pdf | | 3 | IntroductionToCoreJava.pdf | | 4 | JavaCollections.pdf | | 5 | JavaServlet.pdf | +----+----------------------------+ 5 rows in set (0.00 sec)