一、数据类型
截图来源: http://www.runoob.com/mysql/mysql-data-types.html
二、基本语句
1、创建数据表
//主键自增,T_User
CREATE TABLE IF NOT EXISTS `T_User`( `Id` INT UNSIGNED AUTO_INCREMENT, `Name` VARCHAR(100) NOT NULL, `CardNo` VARCHAR(40) NOT NULL, `Birthday` DATE, PRIMARY KEY ( `Id` ) )ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、删除数据表
DROP TABLE T_School;
3、新增数据
INSERT INTO T_User (Name, CardNo, BirthDay) VALUES(‘大王‘, ‘0001‘, NOW());
4、删除数据
//条件删除
DELETE FROM T_User WHERE Id=3;
//清空表格,自增主键不会重置
DELETE FROM T_User;
//或者,自增主键重置
TRUNCATE TABLE
T_User;
5、更新数据
UPDATE T_User SET Name=‘女王‘, CardNo=‘NX_01‘ WHERE Id=4;
6、查询数据
//查询表所有数据
SELECT * FROM T_User;
//条件查询
SELECT * FROM T_User WHERE Id>2 AND Name IS NOT NULL;
//分组
SELECT Name FROM T_User GROUP BY Name;
//排序,默认ASC,顺序
SELECT * FROM T_User ORDER BY Id DESC;
//INNER JOIN(内连接,或等值连接:获取两个表中字段匹配关系的记录。
//LEFT JOIN(左连接:获取左表所有记录,即使右表没有对应匹配的记录。
//RIGHT JOIN(右连接:与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
SELECT TU.* FROM T_User TU
INNRT JOIN T_School TS ON TS.Id = TU.SchoolId
WHERE TS.`LEVEL` = 1;
//UNION ALL: 返回所有结果集,包含重复数据
//UNION DISTINCT: 删除结果集中重复的数据,默认去重
SELECT Id, Name FROM T_User WHERE ClassName=‘三年二班‘
UNION ALL
SELECT Id, Name FROM T_User WHERE ClassName=‘三年五班‘
//统计
SELECT COUNT(1) FROM T_User;
7、表字段修改
//新增字段 ALTER TABLE T_User ADD ClassName VARCHAR(100) NOT NULL; //删除字段 ALTER TABLE T_User DROP CardNo; //修改字段数据属性 ALTER TABLE T_User MODIFY Name BIGINT NOT NULL DEFAULT 100; //修改字段名称 ALTER TABLE T_User CHANGE Name RealName VARCHAR(100);
三、其他函数
1、判断
SELECT IF(SEX = 1, ‘男‘, ‘女‘) SEX FROM T_USER;
2、逗号拼接
SELECT GROUP_CONCAT(Name) FROM T_User LIMIT 10;
3、判空
SELECT IFNULL(CardNo, ‘0000‘) CardNo FROM T_User WHERE Id>10;
4、转换数据类型
//类型转换 SELECT CAST(Id AS CHAR) FROM T_User; //拼接个空字符串,隐式转换 SELECT CONCAT(Id,‘‘) FROM T_User;
5、分页及统计行数
//方法一 SELECT TAB.*, @i Total FROM (SELECT (@i := @i + 1) AS RowNum, B.* FROM book B, (SELECT @i := 0) AS it ) TAB WHERE TAB.RowNum BETWEEN 5 AND 10 //方法二: SET @i=0; SELECT TAB.*, @i Total FROM (SELECT (@i := @i + 1) AS RowNum, B.* FROM book B ) TAB WHERE TAB.RowNum BETWEEN 5 AND 10; SET @i:=NULL;
6、时间格式转换
//yyyy-MM-dd HH:mm:ss date_format(Birthday, ‘%Y-%m-%d %H:%i:%s‘)