在 MySQL 中找到列值以特定子字符串结尾的行?
若要查找行并用新值更新列值,需在列值后使用 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)
广告