使用select like (concat, replace 关键字)
world表结构如下:
name | capital | continent |
---|---|---|
Afghanistan | Kabul | Asia |
Albania | Tirana | Europe |
Algeria | Algiers | Africa |
Andorra | Andorra la Vella | Europe |
Angola | Luanda | Africa |
.... |
name:国家名称
continent:洲份
1. 找出以Y为开头的国家
select name from world where name like "Y%";
2. 找出以Y结尾的国家
select name from world where name like "%Y";
3. 找出包含x字母的国家
select name from world where name like "%x%";
4. 找出所有以C开头的, 并以ia结尾的国家
select name from world where name like "C%ia";
5. 找出所有包含三个或以上a的国家
select name from world where name like "%a%a%a%"
6. 找出第二个字母是t的国家的名字
select name from world where name like "_t%";
7. 找出名字中都有两个字母o, 被另外两个字母相隔着
select name from world where name like "%o__o%";
8. 找出所有4个字母的国家的名字
select name from world where name like "____";
9. 显示所有首都和国家名字相同的国家
select name from world where name = capital;
10. 显示所有首都名字为国家名字加上“ City”
select name from world where concat(name, " City") = capital;
11. 找出首都中出现了国家名字的首都和其国家名字
select capital, name from world where capital like concat("%", name, "%");
12. 找出所有首都和其国家的名字, 而首都是国家名字的延伸(不显示相同)
select capital, name from world where capital like concat("%", name, "%") and capital != name;
13. 找出所有符合上题国家名字的名字和延伸词
select capital, name, replace(capital, name, "") as word from world where capital like concat("%", name, "%") and capital != name;
总结:
- 想找出以xx为开头结尾或含有时使用
like
关键字 - 使用%可匹配任意数量字符, 包括0
- 使用_可匹配一个字符
- 想要组合一个字符串进行查询或显示时, 使用
concat("可以是任意字符", 可以是一个字段名, "可以有任意个")
关键字 - 想要进行字符替换时使用
replace("含有值的数据", "想要替换的值", "要替换为得值")