sql入门

  1 =======================================================================================================================
  2 
  3 --------------------------------------------------------------------------------------------------
  4 一.数据库
  5     1.创建数据库
  6         create database [if not exists] db_name [character set xxx] [collate xxx]
  7         *创建一个名称为mydb1的数据库。
  8             create database mydb1;
  9         *创建一个使用utf8字符集的mydb2数据库。
 10             create database mydb2 character set utf8;
 11         *创建一个使用utf8字符集,并带校对规则的mydb3数据库。
 12             create database mydb3 character set utf8 collate utf8_bin ;
 13     2.查看数据库
 14         show databases;查看所有数据库
 15         show create database db_name; 查看数据库的创建方式
 16     3.修改数据库
 17         alter database db_name [character set xxx] [collate xxxx]
 18     4.删除数据库
 19         drop database [if exists] db_name;
 20     5.使用数据库
 21         切换数据库 use db_name;
 22         查看当前使用的数据库 select database();
 23 --------------------------------------------------------------------------------------------------
 24 二、表
 25     1.创建表
 26             create table tab_name(
 27                 field1 type,
 28                 field2 type,
 29                 ...
 30                 fieldn type
 31             )[character set xxx][collate xxx];
 32             
 33             ****java和mysql的数据类型比较
 34                 String  ----------------------  char(n) varchar(n) 255  65535
 35                 byte short int long float double -------------- tinyint  smallint int bigint float double
 36                 boolean ------------------ bit 0/1
 37                 Date ------------------ Date、Time、DateTime、timestamp
 38                 FileInputStream FileReader  ------------------------------ Blob Text
 39                 
 40                 *创建一个员工表employee
 41                 create table employee(
 42                     id int primary key auto_increment ,
 43                     name varchar(20),
 44                     gender bit default 1,
 45                     birthday date,
 46                     entry_date date,
 47                     job varchar(20),
 48                     salary double,
 49                     resume text
 50                 );
 51                 
 52                 约束:
 53                     primary key
 54                     unique
 55                     not null
 56                     auto_increment 主键字段必须是数字类型。
 57                     外键约束
 58         2.查看表信息
 59             desc tab_name 查看表结构
 60             show tables 查看当前数据库中的所有的表
 61             show create table tab_name    查看当前数据库表建表语句 
 62         3.修改表结构
 63                 (1)增加一列
 64                     alter table tab_name add [column] 列名 类型;
 65                 (2)修改一列类型
 66                     alter table tab_name modify 列名 类型;
 67                 (3)修改列名
 68                     alter table tab_name change [column] 列名 新列名 类型;
 69                 (4)删除一列
 70                     alter table tab_name drop [column] 列名;
 71                 (5)修改表名
 72                     rename table 表名 to 新表名;
 73                 (6)修该表所用的字符集            
 74                     alter table student character set utf8;
 75                     
 76             4.删除表
 77                 drop table tab_name;
 78             
 79             
 80 --------------------------------------------------------------------------------------------------
 81 三、表记录
 82     1.增加一条记录insert
 83         insert into tab_name (field1,filed2,.......) values (value1,value2,.......);
 84         *插入的数据应与字段的数据类型相同。
 85         *数据的大小应在列的规定范围内,例如:不能将一个长度为80的字符串加入到长度为40的列中。
 86         *在values中列出的数据位置必须与被加入的列的排列位置相对应。
 87         *字符和日期型数据应包含在单引号中'zhang' '2013-04-20'
 88         *插入空值:不指定某列的值或insert into table value(null),则该列取空值。
 89         *如果要插入所有字段可以省写列列表,直接按表中字段顺序写值列表insert into tab_name values(value1,value2,......);
 90         
 91         *练习:使用insert语句向表中插入三个员工的信息。
 92         insert into emp (name,birthday,entry_date,job,salary) values ('张飞','1990-09-09','2000-01-01','打手',999);
 93         insert into emp (name,birthday,entry_date,job,salary) values ('关羽','1989-08-08','2000-01-01','财神',9999);
 94         insert into emp (name,birthday,entry_date,job,salary) values ('赵云','1991-07-07','2000-01-02','保安',888);
 95         insert into emp values (7,'黄忠',1,'1970-05-05','2001-01-01','战神',1000,null);
 96 
 97     2.修改表记录 
 98             update tab_name set field1=value1,field2=value2,......[where 语句]
 99             *UPDATE语法可以用新值更新原有表行中的各列。
100             *SET子句指示要修改哪些列和要给予哪些值。
101             *WHERE子句指定应更新哪些行。如没有WHERE子句,则更新所有的行。
102             *实验:
103                 将所有员工薪水修改为5000元。
104                 update emp set salary=5000;
105                 将姓名为’zs’的员工薪水修改为3000元。
106                 update emp set salary=3000 where name='zs';
107                 将姓名为’ls’的员工薪水修改为4000元,job改为ccc。
108                 update emp set salary=4000,job='ccc' where name='zs';
109                 将wu的薪水在原有基础上增加1000元。    
110                 update emp set salar=salary+4000 where name='wu';
111                 
112     3.删除表操作
113             delete from tab_name [where ....]
114             *如果不跟where语句则删除整张表中的数据
115             *delete只能用来删除一行记录,不能值删除一行记录中的某一列值(这是update操作)。
116             *delete语句只能删除表中的内容,不能删除表本身,想要删除表,用drop
117             *同insert和update一样,从一个表中删除记录将引起其它表的参照完整性问题,在修改数据库数据时,头脑中应该始终不要忘记这个潜在的问题。
118             *TRUNCATE TABLE也可以删除表中的所有数据,词语句首先摧毁表,再新建表。此种方式删除的数据不能在事务中恢复。
119             *实验:
120                 删除表中名称为’zs’的记录。
121                 delete from emp where name='黄忠';
122                 删除表中所有记录。
123                 delete from emp;
124                 使用truncate删除表中记录。
125                 truncate table emp;
126                     
127 
128         4.select操作
1291select [distinct] *|field1,field2,......   from tab_name 其中from指定从哪张表筛选,*表示查找所有列,也可以指定一个列列表明确指定要查找的列,distinct用来剔除重复行。
130                 *实验:
131                     查询表中所有学生的信息。
132                     select * from exam;
133                     查询表中所有学生的姓名和对应的英语成绩。
134                     select name,english from exam;
135                     过滤表中重复数据。
136                     select distinct english from exam;
1372select 也可以使用表达式,并且可以使用 as 别名
138                     在所有学生分数上加10分特长分显示。
139                     select name,english+10,chinese+10,math+10 from exam;
140                     统计每个学生的总分。
141                     select name,english+chinese+math from exam;
142                     使用别名表示学生总分。
143                     select name,english+chinese+math as 总成绩 from exam;
144                     select name,english+chinese+math 总成绩 from exam;
145                     select name english from exam;
1463)使用where子句,进行过滤查询。
147                      *练习:
148                     查询姓名为XXX的学生成绩
149                     select * from exam where name='张飞';
150                     查询英语成绩大于90分的同学
151                     select name,english from exam where english>90;
152                     查询总分大于200分的所有同学
153                     select name,math+english+chinese as 总成绩 from exam where math+english+chinese>200 ;
154                     *where字句中可以使用:
155                             *比较运算符:    
156                                         > < >= <= <>  
157                                         between 10 and 20 值在10到20之间  
158                                         in(10,20,3)值是10或20或30
159                                         like '张pattern' pattern可以是%或者_,如果是%则表示任意多字符,此例中张三丰 张飞 张abcd ,如果是_则表示一个字符张_,张飞符合。张
160                                         Is null
161                                         
162                             *逻辑运算符
163                                 在多个条件直接可以使用逻辑运算符 and or not
164                     *实验
165                         查询英语分数在 80-100之间的同学。
166                          select name ,english from exam where english between 80 and 100;
167                         查询数学分数为75,76,77的同学。
168                         select name ,math from exam where math in (75,76,77);
169                         查询所有姓张的学生成绩。
170                         select * from exam where name like '张%';
171                         查询数学分>70,语文分>80的同学。
172                         select name from exam where math>70 and chinese >80;
173                         查找缺考数学的学生的姓名
174                         select name from exam where math is null;
1754Order by 指定排序的列,排序的列即可是表中的列名,也可以是select 语句后指定的别名。
176                     Asc 升序、Desc 降序,其中asc为默认值
177                     ORDER BY 子句应位于SELECT语句的结尾。
178                 *练习:
179                     对数学成绩排序后输出。
180                     select * from exam order by math;
181                     对总分排序按从高到低的顺序输出
182                     select name ,(ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0)) 总成绩 from exam order by 总成绩 desc;
183                     对姓张的学生成绩排序输出
184                     select name ,(ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0)) 总成绩 from exam where name like '张%' order by 总成绩 desc;
1855)聚合函数:技巧,先不要管聚合函数要干嘛,先把要求的内容查出来再包上聚合函数即可。
186                 count(列名)
187                     统计一个班级共有多少学生?先查出所有的学生,再用count包上
188                      select count(*) from exam;
189                     统计数学成绩大于70的学生有多少个?
190                      select count(math) from exam where math>70;
191                     统计总分大于250的人数有多少?
192                         select count(name) from exam where (ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0))>250;
193                 sum(列名)
194                     统计一个班级数学总成绩?先查出所有的数学成绩,再用sum包上
195                         select sum(math) from exam;
196                     统计一个班级语文、英语、数学各科的总成绩
197                         select sum(math),sum(english),sum(chinese) from exam;
198                     统计一个班级语文、英语、数学的成绩总和
199                         select sum(ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0)) as 总成绩 from exam; 
200                     统计一个班级语文成绩平均分
201                             select sum(chinese)/count(*) from exam ;
202                     注意:sum仅对数值起作用,否则会报错。
203             AVG(列名):
204                         求一个班级数学平均分?先查出所有的数学分,然后用avg包上。
205                             select avg(ifnull(math,0)) from exam;
206                         求一个班级总分平均分
207                             select avg((ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0))) from exam ;
208             MaxMin
209                         求班级最高分和最低分(数值范围在统计中特别有用)
210                         select Max((ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0))) from exam;
211                         select Min((ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0))) from exam;
212     
2136group by字句,其后可以接多个列名,也可以跟having子句对group by 的结果进行筛选。
214                         练习:对订单表中商品归类后,显示每一类商品的总价
215                             select product,sum(price) from orders group by product;
216                         练习:查询购买了几类商品,并且每类总价大于100的商品
217                                 select product,sum(price) from orders group by product having sum(price)>100;
218                 !~havingwhere 的差别: where语句用在分组之前的筛选,having用在分组之后的筛选,having中可以用合计函数,where中就不行。使用where的地方可以用having替代。
219                             练习:查询商品列表中除了橘子以外的商品,每一类商品的总价格大于500元的商品的名字
220                                 select product,sum(price) from orders where product<>'桔子'group by product having sum(price)>500;
221 
222 
2237)重点:Select from where group by having order by 
224                         Mysql在执行sql语句时的执行顺序:from where select group by having order by
225                 *分析:        
226                     select math+english+chinese as 总成绩 from exam where 总成绩 >250; ---- 不成功
227                     select math+english+chinese as 总成绩 from exam having 总成绩 >250; --- 成功
228                     select math+english+chinese as 总成绩 from exam group by 总成绩 having 总成绩 >250; ----成功
229                     select  math+english+chinese as 总成绩 from exam order by 总成绩;----成功
230                     select * from exam as 成绩 where 成绩.math>85; ---- 成功
231             
232             
233 --------------------------------------------------------------------------------------------------
234 四、约束
235         
236     1.创建表时指定约束:
237             create table tb(
238                 id int primary key auto_increment,
239                 name varchar(20) unique not null,
240                 ref_id int,
241                  foreign key(ref_id) references tb2(id)
242             );
243             
244             create table tb2(
245                 id int primary key auto_increment
246             );
247             
248 
249     2.外键约束:
2501)增加外键:
251                 可以明确指定外键的名称,如果不指定外键的名称,mysql会自动为你创建一个外键名称。
252                 RESTRICT : 只要本表格里面有指向主表的数据, 在主表里面就无法删除相关记录。
253                 CASCADE : 如果在foreign key 所指向的那个表里面删除一条记录,那么在此表里面的跟那个key一样的所有记录都会一同删掉。
254                 alter table book add [constraint FK_BOOK] foreign key(pubid) references pub_com(id) [on delete restrict] [on update restrict];
255             
2562)删除外键
257                 alter table 表名 drop foreign key 外键(区分大小写,外键名可以desc 表名查看);
258                 
259                 
260     3.主键约束:
2611)增加主键(自动增长,只有主键可以自动增长)
262                 Alter table tb add primary key(id) [auto_increment];
2632)删除主键
264                 alter table 表名 drop primary key
2653)增加自动增长
266                 Alter table employee modify id int auto_increment;
2674)删除自动增长
268                 Alter table tb modify id int;        
269     
270     
271     
272 --------------------------------------------------------------------------------------------------
273 五、多表设计
274     一对一(311教室和20130405班级,两方都是一):在任意一方保存另一方的主键
275     一对多、多对一(班级和学生,其中班级为1,学生为多):在多的一方保存一的一方的主键
276     多对多(教师和学生,两方都是多):使用中间表,保存对应关系
277 
278 
279 --------------------------------------------------------------------------------------------------
280 六、多表查询
281         create table tb (id int primary key,name varchar(20) );
282         create table ta (
283                 id int primary key,
284                 name varchar(20),
285                 tb_id int
286                                         );
287         insert into tb values(1,'财务部');
288         insert into tb values(2,'人事部');
289         insert into tb values(3,'科技部');
290         
291         insert into ta values (1,'刘备',1);
292         insert into ta values (2,'关羽',2);
293         insert into ta values (3,'张飞',3);
294         
295         
296         mysql> select * from ta;
297             +----+------+-------+
298             | id | name | tb_id |
299             +----+------+-------+
300             |  1 | aaa  |     1 |
301             |  2 | bbb  |     2 |
302             |  3 | bbb  |     4 |
303             +----+------+-------+
304         mysql> select * from tb;
305             +----+------+
306             | id | name |
307             +----+------+
308             |  1 | xxx  |
309             |  2 | yyy  |
310             |  3 | yyy  |
311             +----+------+
312     
313         1.笛卡尔积查询:两张表中一条一条对应的记录,m条记录和n条记录查询,最后得到m*n条记录,其中很多错误数据
314             select * from ta ,tb;
315         
316             mysql> select * from ta ,tb;
317                 +----+------+-------+----+------+
318                 | id | name | tb_id | id | name |
319                 +----+------+-------+----+------+
320                 |  1 | aaa  |     1 |  1 | xxx  |
321                 |  2 | bbb  |     2 |  1 | xxx  |
322                 |  3 | bbb  |     4 |  1 | xxx  |
323                 |  1 | aaa  |     1 |  2 | yyy  |
324                 |  2 | bbb  |     2 |  2 | yyy  |
325                 |  3 | bbb  |     4 |  2 | yyy  |
326                 |  1 | aaa  |     1 |  3 | yyy  |
327                 |  2 | bbb  |     2 |  3 | yyy  |
328                 |  3 | bbb  |     4 |  3 | yyy  |
329                 +----+------+-------+----+------+
330         2.内连接:查询两张表中都有的关联数据,相当于利用条件从笛卡尔积结果中筛选出了正确的结果。
331             select * from ta ,tb where ta.tb_id = tb.id;
332             select * from ta inner join tb on ta.tb_id = tb.id;
333         
334             mysql> select * from ta inner join tb on ta.tb_id = tb.id;
335                 +----+------+-------+----+------+
336                 | id | name | tb_id | id | name |
337                 +----+------+-------+----+------+
338                 |  1 | aaa  |     1 |  1 | xxx  |
339                 |  2 | bbb  |     2 |  2 | yyy  |
340                 +----+------+-------+----+------+
341         3.外连接
3421)左外连接:在内连接的基础上增加左边有右边没有的结果
343             select * from ta left join tb on ta.tb_id = tb.id;
344             
345             mysql> select * from ta left join tb on ta.tb_id = tb.id;
346                 +----+------+-------+------+------+
347                 | id | name | tb_id | id   | name |
348                 +----+------+-------+------+------+
349                 |  1 | aaa  |     1 |    1 | xxx  |
350                 |  2 | bbb  |     2 |    2 | yyy  |
351                 |  3 | bbb  |     4 | NULL | NULL |
352                 +----+------+-------+------+------+
3532)右外连接:在内连接的基础上增加右边有左边没有的结果
354                 select * from ta right join tb on ta.tb_id = tb.id;
355                 
356                 mysql> select * from ta right join tb on ta.tb_id = tb.id;
357                 +------+------+-------+----+------+
358                 | id   | name | tb_id | id | name |
359                 +------+------+-------+----+------+
360                 |    1 | aaa  |     1 |  1 | xxx  |
361                 |    2 | bbb  |     2 |  2 | yyy  |
362                 | NULL | NULL |  NULL |  3 | yyy  |
363                 +------+------+-------+----+------+
364                 
3653)全外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
366                 select * from ta full join tb on ta.tb_id = tb.id; --mysql不支持全外连接
367                 select * from ta left join tb on ta.tb_id = tb.id 
368                 union
369                 select * from ta right join tb on ta.tb_id = tb.id;
370                 
371                 mysql> select * from ta left join tb on ta.tb_id = tb.id
372                     -> union
373                     -> select * from ta right join tb on ta.tb_id = tb.id; --mysql可以使用此种方式间接实现全外连接
374                 +------+------+-------+------+------+
375                 | id   | name | tb_id | id   | name |
376                 +------+------+-------+------+------+
377                 |    1 | aaa  |     1 |    1 | xxx  |
378                 |    2 | bbb  |     2 |    2 | yyy  |
379                 |    3 | bbb  |     4 | NULL | NULL |
380                 | NULL | NULL |  NULL |    3 | yyy  |
381                 +------+------+-------+------+------+
原文地址:https://www.cnblogs.com/DLzhang/p/4167010.html