带下划线的 MySQL LIKE 查询

2021-11-20 00:00:00 sql mysql

我有下表images:

+----+--------------+
| id |   img_path   |
+----+--------------+
| 1  | abc_1.jpg    |
| 2  | abc_2.jpg    |
| 3  | abcde_1.jpg  |
| 4  | abcde_2.jpg  |
| 5  | abcdef_1.jpg |
+----+--------------+

我想选择img_pathabc_开头的条目,所以我使用以下查询:

I would like to select the entries that img_path starts with abc_, so I use the following query:

SELECT id FROM images WHERE img_path LIKE 'abc_%'

但它返回所有 5 行.我如何只返回 id = 1 &2(哪个img_pathabc_开头)?

But it returns all 5 rows. How do I only returns id = 1 & 2 ( which img_path starts with abc_) ?

推荐答案

发现 _ 是一个特殊字符.必须使用反斜杠转义.

Found out that _ is a special character. Have to escape with backslashes.

SELECT id FROM images WHERE img_path LIKE 'abc\_%'

按预期返回 2 行

相关文章