9. 建表语句解析
? 空值和默认值
– page_id INT NOT NULL DEFAULT 0
? 存储引擎
– ENGINE=MyISAM
– ENGINE=InnoDB
– ENGINE=BRIGHTHOUSE
? 编码格式
– CHARACTER SET=utf8
? 表注释、字段注释
– COMMENT ‘页面ID’
10. 建表语句解析
? 忽略已存在的表
– CREATE TABLE IF NOT EXISTS soj_dtl (…);
? 创建临时表
– CREATE TEMPORARY TABLE soj_dtl (…);
? 复制表结构
– CREATE TABLE soj_dtl LIKE soj_dtl_template;
? 将查询结果保存为表
– CREATE TABLE soj_dtl AS
SELECT * FROM soj_dtl WHERE page_id != 0;
11. 表的其他操作
? 删除表
– DROP TABLE IF EXISTS soj_dtl;
? 清空表
– TRUNCATE TABLE soj_dtl;
– 等价于DROP + CREATE
? 重命名
– RENAME TABLE soj_dtl TO soj_dtl_old;
12. 表的其他操作
? 修改表结构
– ALTER TABLE soj_dtl ADD COLUMN url VARCHAR(255);
– ALTER TABLE soj_dtl CHANGE COLUMN url long_url
VARCHAR(500);
– ALTER TABLE soj_dtl DROP COLUMN long_url;
? 索引
? 自增ID
– id INT AUTO_INCREMENT PRIMARY KEY
? 记录更新时间
– ON UPDATE CURRENT_TIMESTAMP
13. 插入数据
? 使用INSERT INTO插入单条或多条记录
– INSERT INTO soj_dtl (log_time, page_id, guid)
VALUES (NOW(), 1, ‘AAA’), (NOW(), 2, ‘BBB’);
? 将查询结果插入表
– INSERT INTO soj_dtl SELECT * FROM soj_dtl_old;
? 使用LOAD DATA批量导入数据
– LOAD DATA INFILE ‘/tmp/mydata’ INTO TABLE soj_dtl
FIELDS TERMINATED BY ‘,’;
? 唯一键冲突
– REPLACE INTO
– ON DUPLICATE KEY UPDATE
14. 查询数据
? 普通查询
– SELECT log_time, page_id FROM soj_dtl
WHERE page_id IN (1, 2, 3)
ORDER BY log_time DESC
LIMIT 10;
? 分组查询
– SELECT page_id, COUNT(*) FROM soj_dtl
GROUP BY page_id
HAVING COUNT(*) > 100;
15. SQL表达式
? 字面量:数字、字符串、日期字符串
? 运算符:+, -, *, /, MOD
? 比较运算符:=, !=, <>, >, >=, <, <=, IS (NOT) NULL
(NOT) IN, BETWEEN AND, LIKE, RLIKE, REGEXP
? 逻辑运算符:AND, OR, NOT
? 位运算符
? 运算符优先级
? 变量
? 函数
18. 导出查询结果
? 使用SQL
– SELECT * FROM soj_dtl
INTO OUTFILE ‘/tmp/soj_dtl.csv’
FIELDS TERMINATED BY ‘,’ OPTIONALLY ENCLOSED BY ‘”’
LINES TERMINATED BY ‘n’;
? 使用mysqldump程序
– mysqldump -h10.20.8.41 -uxxx -pxxx dw_db soj_dtl
--compact --skip-lock-tables >soj_dtl.txt
19. 更新和删除
? 更新数据
– UPDATE soj_dtl SET guid = ‘CCC’ WHERE page_id = 1;
– UPDATE soj_dtl a, pagename_lkp b
SET a.page_name = b.page_name
WHERE a.page_id = b.page_id;
? 删除数据
– DELETE FROM soj_dtl WHERE page_id = 1
ORDER BY log_time LIMIT 10;
20. 函数概览
? 函数类别
– 聚合函数:COUNT(DISTINCT), SUM, AVG, STD, MAX, MIN
– 流程控制:IF, IFNULL, CASE WHEN
– 类型转换:CAST
– 字符串操作:SUBSTRING, CONCAT, TRIM, LOWER
– 数值操作:ROUND, RAND, POW, SIN
– 时间日期:NOW, DATE_ADD, HOUR, DATE_FORMAT,
UNIX_TIMESTAMP, FROM_UNIXTIME
? 自定义函数
22. 使用索引
? 创建索引
– ALTER TABLE soj_dtl ADD INDEX idx1 (page_id, log_time);
? 删除索引
– ALTER TABLE soj_dtl DROP INDEX idx1;
? 查看建表语句(含索引)
– SHOW CREATE TABLE soj_dtl;
? 查看索引大小
– SHOW TABLE STATUS LIKE ‘soj_dtl’;
? 分析查询语句是否用到了索引
– EXPLAIN SELECT * FROM soj_dtl WHERE log_time < NOW();