MySQL:在示例表“bar”中刪除包含字串“foo”的所有行?


若要刪除表“bar”中包含字串“foo”的所有行,您需要使用 LIKE 運算子。

為了理解上述語法,讓我們建立一個名為“bar”的示例表。建立表的查詢如下。在建立下面的表之後,我們將始終使用 INSERT 命令插入包含字串“foo”的記錄−

mysql> create table bar
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Words longtext,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.61 sec)

現在,您可以使用 insert 命令在表中插入一些記錄。在插入記錄時也添加了字串“foo”。查詢如下−

mysql> insert into bar(Words) values('Javafoo');
Query OK, 1 row affected (0.14 sec)
mysql> insert into bar(Words) values('fooMySQL');
Query OK, 1 row affected (0.19 sec)
mysql> insert into bar(Words) values('Introductiontofoo C and C++');
Query OK, 1 row affected (0.22 sec)
mysql> insert into bar(Words) values('Introduction to Node.js');
Query OK, 1 row affected (0.19 sec)
mysql> insert into bar(Words) values('Introduction to Hibernate framework');
Query OK, 1 row affected (0.17 sec)

以下是使用 select 語句顯示錶中所有記錄的查詢。查詢如下−

mysql> select *from bar;

以下是輸出−

+----+-------------------------------------+
| Id | Words                               |
+----+-------------------------------------+
|  1 | Javafoo                             |
|  2 | fooMySQL                            |
|  3 | Introductiontofoo C and C++         |
|  4 | Introduction to Node.js             |
|  5 | Introduction to Hibernate framework |
+----+-------------------------------------+
5 rows in set (0.00 sec)

以下是從表“bar”中刪除包含字串“foo”的所有行的查詢−

mysql> delete from bar where Words like '%foo'
   -> or Words like '%foo%'
   -> or Words like 'foo%';
Query OK, 3 rows affected (0.20 sec)

現在再次檢查表記錄。查詢如下−

mysql> select *from bar;

以下是輸出−

+----+-------------------------------------+
| Id | Words                               |
+----+-------------------------------------+
|  4 | Introduction to Node.js             |
|  5 | Introduction to Hibernate framework |
+----+-------------------------------------+
2 rows in set (0.00 sec)

現在檢視上面的示例輸出,所有包含字串“foo”的記錄均已從表“bar”中刪除。

更新於: 2019-07-30

1K+ 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告