`
海角七号
  • 浏览: 17423 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

MySQL学习笔记(二)

阅读更多

一、插入数据insert:

insert into t_stu
(stuname,stuage,stuaddress)
values
('tom',23,'北京'),
('jack',22,'上海'),
('rose',22,'美国');

 insert语句需要注意的:

  1. insert 语句中列的数量和值的数量必须相同;
  2. 每个值的数据类型,精度和小数位数必须和列的要求相匹配;
  3. 列的值要符合列的约束;
  4. 如果列有默认值,可以使用关键字default来插入默认值。

二、MySQL中的算术运算符:

 1、逻辑运算符:

    =(等于)

    <>或!=(不等于)

    <(小于)

    >(大于)

    <=(小于等于)

    >=(大于等于)

    between(在指定的两个值之间,包括这两个值)

2、关系运算符:

     and

     or

     not

三、修改表中数据(update):

update t_stu set stuname='jack'[where id=1] ;--修改id为1的名字为jack,  如果不写中括号里面的where条件,则会把所有的姓名都改为jack
update t_stu set stuage=stuage+1;   --将表中stuage这一列的数都加一
update t_stu set stuage=23 where id id(1,2,4,5); --将id号为1,2,4,5的        stuage改为23 
update t_stu set stuage=27 where id between 1 and 4;--将id号在1和4之间的stuage改为27,相当于where id>=1 and id<=4;
update t_stu set stuage=24 where stuage is null;
update t_stu set stuage=21 where stuage is not null;

 四、删除:

1、delete(只删除数据,不删除表)

delete from t_stu where id=1;  --将id为1的行删除

 2、trunate table 

truncate table t_stu;  --删除t_stu表中的所有数据

 (trunate table 用于删除表中的所有记录,但该语句不包含where语句,该操作运行速度比delete语句快)

 五、三大范式:

1、确保每列的原子性

2、在第一范式的基础上,确保每列和主键相关

3、在第二范式的基础上,确保每列都和主键直接相关,而不是间接相关

(当对增删改查带来极大便利的情况下,可以允许违反第三范式,但是这必定会造成数据冗余)

 

在实际操作中我们会采取拆表操作

六、创建外键:

alter table t_user add constraint fk_user_class foreign key(classid) references class(id);

 七、删除外键:

alter table t_user drop foreign key fk_user_class;

 表中有外键的时候,需要注意以下几点:

1、子表中外键列中添加的数据必须在主表的主键中存在

2、外键列的数据类型及长度必须和主表的主键的数据类型及长度相同

3、删除主表数据时,如果有字表引用,则删除失败

八、去除重复的查询

select distinct vend_id from products;

 九、分页查询:

select id,stuname,stuage,stuaddress from t_stu limit 0,5;--第一页从0开始往后数5个显示出来
select id,stuname,stuage,stuaddress from t_stu limit 5,5;--第二页从5开始往后数5个显示出来

 十、排序查询:

1、升序:

select prod_id,prod_name,prod_price from products order by prod_price[asc];--asc表示升序,不写时默认是升序

 2、降序:

select prod_id,prod_name,prod_price from products order by prod_price desc;

 3、按多列排序:

select prod_id,prod_name,vend_id,prod_price from products order by prod_price asc,prod_name asc;--先按prod_price升序排列,当prod_price相同时再按prod_name排序

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics