MySQL语句小总结

 数据定义语言 ddl 用来定义数据库对象 数据库database 表table 列column等 关键字 :创建create 修改 alter 删除drop
 数据操作语言 dml 用来对数据库中的记录进行更新 关键词insert 删除delete 更新update
 数据查询语言 dql 用来查询数据库中表的记录 关键词select from where 

一库

创建一个库
create database 库名
创建一个库并设置编码
create database 库名 set charaterset utf-8
删除一个库
drop database
查看当前正在操作数据库
select database

二 表

创建表
create table 表名(
字段名 类型(长度)【约束】
字段名 类型(长度) )

单表约束
主键约束 primary key 要求被修饰的字段:唯一和非空
唯一约束 unique 要求被修饰的字段 唯一
非空约束 not null
auto -increament 自增
查看数据库表
show tables
查看表结构
desc 表名
删除一张表
drop table 表名

修改表
添加一列
alter table 表名 add 字段名 类型(长度) 【约束】
修改列的长度 约束 类型
alter table 表名 modify 要修饰的字段名 类型(长度) 【约束】
修改列名
alter table 表名 change 旧列名 新列名 类型 (长度) 约束
删除表的列
alter table 表名 drop 列名
修改表名
rename table 表名 to 新表名
修改表的字符集
alter table 表名 character set 编码

三 更新记录

1.插入记录
insert into 表(列名1,列名2) values(值1,值2)
insert into 表 values(值1,值2)
2.更新记录
不带条件
update 表名 set 字段名=‘值’,字段名=‘值’
update 表名 set 字段名=‘值’where uid=1
3删除记录
delect from 表名 where 条件
删除后id不会重置 删除时候是一条记录一条记录的删除 它配合事务可以将删除数据找回
trancate删除 将整个表摧毁 再创建一张一模一样的表 删除的数据无法找回 使用方法和delect一样

四查询操作

1.简单查询
查询所有商品
select * from product
查询所有商品使用表别名
select *from product as p
查询商品名 使用列别名
select pname as p from product
去掉重复值(按价格)
select distinct(price) from product
2.条件查询
查询商品中名字带有士的
select * from product where pname like ‘%士%’
查询商品id在(3,6,9)内的
select * from product where id in(3,6,9)
3.排序
select * from product order by price asc/desc
4.聚合
常用聚合函数 sum()求和 avg()平均 max()最大值 count()
获得所有商品的价格总价
select sum from product
5.分组
先根据某一列的属性分组
根据cid 分组 分组统计商品平均价值 并且平均价值大于1200
select avg from product group by cid having avg>1200
查询总结
select 在其后是要查询的字段
from 查询得表
where 条件
groupby 分组
having 分组后的条件
orderby 必须放在最后面 asc/desc
6.内连接查询 关键字inner join inner可以省略
隐式内连接
select * from A,B where 条件
select * from category c, product p where c.cid=p.category_id
显示内连接
select * from A inner join B on 条件
7.外连接查询
左外连接
select * from A left outer join B on 条件
select * from category left outer join product on cid=category_id
右外连接
select * from A right outer join B on 条件
8子查询
一条sql语句结果作为另一条select语法一部分
select * from product where category_id=(select cid from category where cname =’化妆品’)

五声明外键约束

alter table 从表 add【contraint】[外键名称] foreign key(从表外键字段名)references 主表(主表的主键)
alter table (product) add foreign key (sno) references stu(sid);
一对多建表原则
在多的一方创建一个字段 字段作为外键指向一的一方的主键
多对多建表原则
创建第三张表 至少两个字段 分别作为外键指向各自一方的主键

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值