- 登录
1.mysql -u username -p; - 显示所有数据库
show databases; - 切换到XX数据库
use databasename; - 显示databasename下的所有表
show tables; - 创建删除表、数据库
mysql -u root -p create 数据库名;
mysql -u root -p drop 数据库名;
create table 表名(column_name column_type not null auto_increment primary key); - 查看表数据
select * from tablename; - 查看表结构
desc tablename; - 查看表索引
show index from tablename; - 插入表数据
insert into tablename(field….) values(value….); - 更新表数据
update tablename set fieldname=”xx” [where clause]; - 删除表数据
delete from 表名 [where clause]; - 查询表数据
select * from 表名 [where clause]; - 排序
select * from 表名 [where clause] order by field1,field2… [asc|desc] - 分组
select column_name,function(column_name) from tablename where clause group by column_name having function(column_name) operator value order by …. - 连接
1.内连接(交集)<==>where
select a.* ,b.* from a inner join b on a.id=b.id;
2.左连接(读取左边所有数据,右表没有用NULL填充)
select a.* ,b.* from a left join b on a.id=b.id;
3.右连接(与左连接相反)
select a.* ,b.* from a rightjoin b on a.id=b.id; - alter命令
1.添加主外键、约束
alter table 表名 add constraint 键名 foreign key(列名) refereneces 表名(列名);
2.删除、添加、修改表字段
alter table 表名 drop 字段名;
alter table 表名 add 字段名 [after 字段名|first];默认最后;
alter table 表名 change 原字段名 新字段名 新数据类型 ;
alter table 表名 modify 原字段名 新数据类型 not null [default 默认值];
3.删除默认值
alter table 表名 alter 字段名 drop default;
4.修改表名
alter table 表名 rename to 新表名; - 索引(参考 http://feiyan.info/16.html)
1.创建
create [unique | fulltext] indexname on tablename(fieldname(length));默认btree索引;
2.删除
drop index [indexname] on tablename; - 存储过程(参考 http://blog.sina.com.cn/s/blog_52d20fbf0100ofd5.html )
mysql> DELIMITER //
mysql> CREATE PROCEDURE proc1(OUT s int)
-> BEGIN
-> SELECT COUNT(*) INTO s FROM user;
-> END
-> //
mysql> DELIMITER ; - 复制表
insert into tableA select * from tableB; - delete ,drop ,truncat区别
delete 删除表数据,可精确删除,可回滚;
truncate 清除数据,不可精确删除,不可回滚;
drop 删除表;drop table tablename; - 分页
select * from tablename limit[offset] 页面大小;
select * from tableA limit 0,5;–第1-6条记录; - sql语句执行顺序
from–on–inner join–where–group by–count等聚合函数–having–select–distinct–order by–top
MySQL基本语句
最新推荐文章于 2024-09-02 14:48:18 发布