LIKE 操作符用于在 WHERE 子句中搜索列中的指定模式。
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern;
在本教程中,我们将使用 Web3 样本数据库。
下面是选自 "Websites" 表的数据:
+----+--------------+---------------------------+-------+---------+ | id | name | url | alexa | country | +----+--------------+---------------------------+-------+---------+ | 1 | Google | https://www.google.cm/ | 1 | USA | | 2 | 淘宝 | https://www.taobao.com/ | 13 | CN | | 3 | 芝麻教程 | http://www.web3.xin/ | 4689 | CN | | 4 | 微博 | http://weibo.com/ | 20 | CN | | 5 | Facebook | https://www.facebook.com/ | 3 | USA | | 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND | +----+---------------+---------------------------+-------+---------+
SQL LIKE 操作符实例
下面的 SQL 语句选取 name 以字母 "G" 开始的所有客户:
SELECT * FROM Websites WHERE name LIKE 'G%';
执行输出结果:
mysql> select * from websites where name like 'G%'; +----+--------+------------------------+-------+---------+ | id | name | url | alexa | country | +----+--------+------------------------+-------+---------+ | 1 | Google | https://www.google.cm/ | 1 | USA | +----+--------+------------------------+-------+---------+ 1 row in set (0.00 sec)
提示:"%" 符号用于在模式的前后定义通配符(缺省字母)。您将在下一章中学习更多有关通配符的知识。
下面的 SQL 语句选取 name 以字母 "k" 结尾的所有客户:
SELECT * FROM Websites WHERE name LIKE '%k';
执行输出结果:
mysql> select * from websites where name like '%k'; +----+----------+---------------------------+-------+---------+ | id | name | url | alexa | country | +----+----------+---------------------------+-------+---------+ | 5 | Facebook | https://www.facebook.com/ | 3 | USA | +----+----------+---------------------------+-------+---------+ 1 row in set (0.00 sec)下面的 SQL 语句选取 name 包含模式 "oo" 的所有客户:
select * from websites where name like '%oo%';执行输出结果:
mysql> select * from websites where name like '%oo%'; +----+----------+---------------------------+-------+---------+ | id | name | url | alexa | country | +----+----------+---------------------------+-------+---------+ | 1 | Google | https://www.google.cm/ | 1 | USA | | 5 | Facebook | https://www.facebook.com/ | 3 | USA | +----+----------+---------------------------+-------+---------+ 2 rows in set (0.00 sec)