下面为个人看《MySQL必知必会》时做的笔记,感觉《MySQL必知必会》属于一般笔记基础的书,可以巩固一下之前的基础。下面的SQL语句大部分是dede_scores表的,下面是创建表的语句:
CREATE TABLE `dede_scores` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`titles` char(15) NOT NULL,
`icon` smallint(6) unsigned DEFAULT '0',
`integral` int(10) NOT NULL DEFAULT '0',
`isdefault` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `integral` (`integral`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=gbk
一、连接
1、登录MySQL: mysql -u 用户名 -p -h 域名 -P 端口
2、显示所有的数据库:show databases;
3、创建一个数据库:create database test_db;
4、使用|切换表:use xxx【数据库名字】
5、显示数据库下面的所有表:show tables;
6、显示表结果:show columns from xxx; 或者:describe xxx;
7、显示广泛的服务器状态信息:show status;
8、显示创建数据库的语句:show create database xxx;
9、显示创建表的语句:show create table xxx;
10、显示授权用户的权限:show grants;
二、检索
1、查询所有列:select * from dede_scores;
2、指定查询多个列:select id,name from dede_scores;
3、DISTINCT使用:select distinct id,name from dede_scores;【只返回不同的id,唯一。注意:除非是指定的列都不同,否则所有的行都会被索引出来】查看例子
4、返回查询结果的前5行:select * from dede_scores limit 5;
5、按照指定的开始行和行数返回查询结果:select * from dede_scores limit 5,5;
6、select dede_scores.id from dede_scores;
7、完全限定表名:select 表名.字段名 from 数据库名.表名
三、排序检索
1、查询排序:select * from dede_scores order by id;
2、按多个列排序:select * from dede_scores order by id, titles;
3、指定排序的方向:select * from dede_scores order by id desc;
asc:升序 、desc:降序, 默认asc
四、过滤数据
1、查询isdefault=1:select * from dede_scores where isdefault = 1;
2、查询isdefault <=1: select * from dede_scores where isdefault <=1;
3、不等于1:select * from dede_scores where isdefault != 1 或者:select * from dede_scores where isdefault <> 1
4、在指定的两个值之间:select * from dede_scores where isdefault between 1 and 2
5、查询字段是否是null:select * from dede_scores where titles is null
五、数据过滤
1、AND 操作符: select * from dede_scores where isdefault > 0 and isdefault < 2
2、OR操作符:select * from dede_scores where id = 1 or id =100;
3、注意:OR和AND同时出现是,AND优先
4、IN操作:select * from dede_scores where isdefault IN (1, 2);
5、IN 和OR具有相同的功能,为什么要使用IN操作符?
5.1、IN操作符语法更清楚更直观
5.2、使用In时,计算的次序更容易管理(因为操作符更少)
5.3、IN操作符一般比OR操作符清单执行更快
5.4、IN操作符可以包含其他的select语句
6、NOT操作符:select * from dede_scores where id not in(1,2)
六、通配符过滤
1、半%操作符:select * from dede_scores where titles like "%帝";
2、全%操作符:select * from dede_scores where titles like "%帝%";
3、中间%操作符:select * from dede_scores where titles like "皇%帝";
4、%除了匹配一个或多个字符外,%还能匹配0个字符
5、虽然似乎%通配符可以匹配任何东西,但有一个例外,即NULL,例如titles的产品名为NULL,那么where titles like "%"是不能匹配到的
6、_操作符:只匹配单个字符而不是多个字符:select * from dede_scores where title like "_帝";
7、通配符使用技巧:
7.1、不要过度使用通配符,能够使用其他操作符达到的,使用其他的操作符
7.2、如果确实要用通配符的,除非绝对有必要,否则不要用在搜索模式的开始处
七、正则表达式搜索
1、REGEXP字符串:select * from dede_scores where titles REGEXP '帝';
2、使用OR匹配:select * from dede_scores where titles REGEXP '帝|将';
3、匹配几个字符之一: select * from dede_scores where titles REGEXP '[帝将]'; 得到的结果为有“帝”和“将”字之一的结果;
4、匹配titles中是否有“.”存在:select * from dede_scores where titles REGEXP '\\.';【使用两个斜杆的原因:MySQL自己解释一个,正则表达式解释另外一个】