在 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)
廣告