视频和讲义中如下两个问题,我觉的好像不对:
查询名字中含有两个 o 的雇员的名字与薪水。
select last_name,salary from employees where last_name REGEXP 'o.{2}'
查询雇员名字中包含 1 个或者两个 o 的雇员姓名与薪水。
select last_name,salary from employees where last_name REGEXP 'o.{1,2}'
一、问题分析:
select last_name,salary from employees where last_name REGEXP 'o.{2}'
我认为这条语句表示含有1个'0',2个或2个以上'.',也就是含有1个以上字母'o',最终返回结果:字符串出现第一个'o'的后面字符长度在2个以上,即满足要求,那么oldLu 也可以被选中。
二、问题验证:
mysql> select * from employees;
+-------------+-----------+-------------+---------+
| employee_id | last_name | email | dept_id |
+-------------+-----------+-------------+---------+
| 1 | asb | gjj@q.com | NULL |
| 2 | adal | aa@da.com | NULL |
| 3 | huli | dfd@qe.3com | NULL |
| 4 | fox | gdfx@gr | NULL |
| 5 | cagayauj | zc | NULL |
| 6 | oldLu | bm | NULL |
| 7 | oldoLu | bj | NULL |
| 8 | oldoLou | sxt | NULL |
+-------------+-----------+-------------+---------+
8 rows in set
mysql> select * from employees where last_name regexp'o.{1,3}';
+-------------+-----------+---------+---------+
| employee_id | last_name | email | dept_id |
+-------------+-----------+---------+---------+
| 4 | fox | gdfx@gr | NULL |
| 6 | oldLu | bm | NULL |
| 7 | oldoLu | bj | NULL |
| 8 | oldoLou | sxt | NULL |
+-------------+-----------+---------+---------+
4 rows in set
mysql> select * from employees where last_name regexp'o.{2,3}';
+-------------+-----------+-------+---------+
| employee_id | last_name | email | dept_id |
+-------------+-----------+-------+---------+
| 6 | oldLu | bm | NULL |
| 7 | oldoLu | bj | NULL |
| 8 | oldoLou | sxt | NULL |
+-------------+-----------+-------+---------+
3 rows in set
mysql> select * from employees where last_name regexp'o.{6,8}';
+-------------+-----------+-------+---------+
| employee_id | last_name | email | dept_id |
+-------------+-----------+-------+---------+
| 8 | oldoLou | sxt | NULL |
+-------------+-----------+-------+---------+
1 row in set
mysql>
如上代码,
select * from employees where last_name regexp'o.{6,8}';
只选中 oldoLou,是因为这个字符串总长为7,出去1个o,还有6个字符长度,不选中oldoLu,是因为oldoLu除去1个o只剩5个字符了不满足 '.{6,8}'。
select * from employees where last_name regexp'o.{2,3}';
选中 oldLu 而不选中 fox,也是因为 fox中的 o后面只有1个字符,不满足'.{2,3}'。
三、疑问(我没找到解决方案)
针对如上的 employees 这个table,我要查询 last_name 有 2个o,也就是只选中“oldoLu”,怎么搞定呢?
同理如何搞定只有1个 o的,即只选中 “fox”和 “oldLu”。
再搞定有 2~3个o的,即只返回 "oldoLu"和 "oldoLou"。