MySQL中sql语句总结

来源:互联网 发布:知行理工官方下载 编辑:程序博客网 时间:2024/06/06 20:40

一.前言

MySQL数据库中的sql语句是否区分大小写,在不同的操作系统中表现不同。
在windows系统中不区分大小写:SELECT * FROM USER WHERE USERNAME='....'select * from user where username='....'查询结果是一样的。
在Linux和Unix系统中字段名、数据库名和表名要区分大小写:select * from TSET.USER where USERNAME ='....'SELECT * FROM TSET.USER WHERE USERNAME='....'的结果是一样的。
详细的mysql操作可参考链接mysql之sql大全

二.基本操作

1.创建数据库 create database db_name;
2.删除数据库drop database db_name
3.创建新表create table table_name(column_name1 type1 [not null default default_value] [primary key],column_name2 type2 [not null default default_value], ... )
4.删除表drop table table_name
5.增加一列alter table table_name add column column_name type [not null default default_value]
6.修改列alter table table_name modify column column_name type [not null default default_value]
7.添加主键alter table table_name add primary key(column_name)
8.常用的增删查改
查询select * from table_name where 范围
插入insert into table_name(field1,field2) values(value1,value2)
删除delete from table_name where 范围
更新update table_name set field1=value1 where 范围
排序select * from table_name order by field1,field2 [desc]
总数select count(*) as totalcount from table_name
求和select sum(field1) as sumvalue from table_name
平均select avg(field1) as avgvalue from table_name
最大select max(field1) as maxvalue from table_name
最小select min(field1) as minvalue from table_name
9.使用外连接
左连接left join:结果集只包括连接表的匹配行,也包括左连接表的所有行。select * from table_name1 a left join table_name2 b on a.id=b.id;
右连接right join:结果集只包括连接表的匹配连接行,也包括右连接表的所有行。
select * from table_name1 a right join table_name2 b on a.id=b.id;
inner join:结果集只包括连接表的匹配行。
select * from table_name1 a inner join table_name2 b on a.id=b.id;
10.分组
一张表,一旦分组完成后,查询后只能得到组相关的信息。
组相关的信息:(统计信息 count,sum,max,min,avg 分组的标准)
select groupid, count(*) from table_name group by field1;