MySQL常见的数据类型和约束
常用命令:
创建数据库:create database name (charset=utf8,视情况写);
查看所有数据库:show database name;
使用数据库: use name;
删除数据库:drop database name;
查看当前数据库中所有表:show tables;
查看表结构:desc name;
创建表:create tables name(字段名 类型及约束,字段名2 类型及约束 .。。。);
常用查询
#查询所有数据
select * from Info; #查所有数据
select Code,Name from Info ;#查特定列
#根据条件查
select * from Info where Code='p001'; #一个条件查询select * from Info where Code='p001' and Nation='n001'; #多条件 并关系 查询
select * from Info where Name='胡军' or Nation='n001'; #多条件 或关系 查询
select * from Car where Price>=50 and Price<=60 ;#范围查询
select * from Car where Price between 50 and 60; #范围查询
#模糊查询
select * from Car where Name like '%型%' ;#通配符代表任意多个字符
select * from Car where Name like '%奥迪%';
select * from Car where Name like '_马%';#_通配符代表任意一个字符
#排序
select * from Car order by Price asc; #按照价格升序排列
select * from Car order by Price desc; #按照价格降序排列
select * from Car order by Price,Oil; #按照两列进行排序,前面的为主要的
#统计函数(聚合函数)
select count(Code) from Car; #查询表中有多少条数据
select max(Price) from Car; #取价格的最大值
select min(Price) from Car; #取价格的最小值
select sum(Price) from Car; #取价格的总和
select avg(Price) from Car;#取价格的平均值
#分组查询
select Brand from Car group by Brand having count(*)>2; #查询所有系列中数量大于2的
sql查询优化:
1.对查询进行优化,应尽量避免全表扫描
2.尽量避免在where字句中使用!=或<>操作符,否则将导致引擎放弃使用索引而进行全表扫描
3.尽量避免模糊查询
4.任何地方都不要使用select * from name ,用具体的字段列表代替 * , 不要返回用不到的任何字段
5.尽量避免大事务操作,提高系统并发能力
6.尽量避免在使用where子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描
等等
sql创建表的一些建议:
1.在所有的字段要加commet注释,方便其他人或自己通过命令查看表的结果信息
2.字段创建时间ctime和修改时间mtime,便于后期排查问题,知道该条记录是何时插入,何时修改
3.所有的字段尽量设置为not null
4.int 符号确定,如果确定整形为非负数,就将int设置为无符号型的,即int unsigned ,可以避免插入负数