分类: Mysql/postgreSQL
2011-09-02 20:29:08
数据库: 表,视图(view),索引(index),触发器(trigger),存储过程(storage procedure),存储函数(storage function),事件调度器(event scheduler),
创建表语法:
CREATE TABLE [IF NOT EXISTS] tb_name
例: CREATE TABLE user ( id INT NOT NULL, Name CHAR(30) NOT NULL,AUTO_INCREMENT KEY);
创建表时,指定引擎
CREATE TABLES users(id INT) ENGINE = InnoDB;
CREATE TABLES users ENGINE = InnoDB;
AUTO_INCREMENT 自动增长
创建表:
CREATE TABLE db_name like db_othername; 只创建表结构
创建users表
CREATE TABLE users ( ID INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,Name VARCHAR(30) NOT NULL,Age TINYINT UNSIGNED NOT NULL,Gender ENUM('F','M') NOT NULL DEFAULT 'M');
设置默认储存引擎:
SET GLOBAL storage_engine = engine_name;
SET SESSION storage_engine = engine_name; 只对当前有效
where字句后可用的:>,<,=,BETWEEN…AND…
SELECT DISTINCT zone FROM zones LIMIT 100; 显示100行且去除重复
GROUP BY 分组
SELECT zone, COUNT(*) FROM mytb GROUP BY zone;
数据导入:#mysql –uroot –p mydb 表名 < /tmp/mydb.sql
mysql>LOAD DATA INFILE ‘/root/table.sql INTO mytb;注:mytb创建的表
order by 字表 DESC 降序; ORDER BY 字表 ASC升序,默认是升序
SHOW INDEXES FROM users;
UNIQUE 唯一性
BTREE | HASH 两种索引类型
修改表结构:
ALTER TABLE tb_name
添加字段:ADD col_name col_ def 添加字段 AFTER col_name在col_name后添加字段,FIRST col_name该字段前加字段
ALTER TABLE user1 ADD Master TINYINT UNSIGNED;
修改字段:
CHANGE old_name new_name col_definat
MODIFY col_name col_definat
例: ALTER TABLE user MODIFY Gender ENUM(‘F’,’M’) NOT NULL DEFAULT ‘M’;
例: ALTER TABLE user CHANGE Master Tutor TINYINT UNSIGNED AFTER Age;
添加索引: ADD {ADD|INDEX} [index_name] [index_type] (col….)
例:ALTER TABLE user ADD INDEX (Age);
删除字段: DROP col_name
删除键:DROP PRIMARY KEY
DROP {INDEX|KEY} index_name
给表重命名:ALTER TABLE user RENAME TO qq 将user命名成qq 或RENAME TABLE user TO qq
插入数据:INSERT INTO tb_name(字段名) VALUE (‘’,’’,’’)
INSERT INTO tb_name VALUE (‘’,’’,’’)
INSERT INTO tb_name SET 字段名=自定义
插入多行:INSERT INTO tb_name (字段名) VALUES (‘’,’’) (‘’,’’) (‘’,’’)
这里的INSERT可以换成REPLACE,区别replace能直接替换主键而不报错,insert不可
修改数据:UPDATE tb_name SET 字段名=设置 WHERE 条件
例: UPDATE user SET Age=21 LIMIT 2; 修改前两行年龄
删除数据:
DELETE FROM tb_name WHERE 条件
TRUNCATE TABLE tb_name 清空数据并恢复初始状态
SELECT LAST_INSERT_ID();
ALTER TABLE user AUTO_INCREMENT=2 设定自动增长的ID号
多表查询:
连接的类型:
交叉连接(很少用到),例:SELECT * FROM user,user2
内连接, 例:SELECT * FROM user,user2 WHERE user.ID=user2.CID表user的字段id和表user2的字段cid连接起来
别名 例:SELECT * FROM user AS A, user2 AS B HWERE A.ID=B.ID
外连接:左外连接、右边连接、
SLECT k.Name,j.Cname FROM user AS k, LEFT JOIN user2 AS j ON k.CID=J.CID
全外连接,自连接
例:SELECT k1.NAME,k2.Name FROM user AS k1, user2 AS k2 WHERE k1.Age=k2.UID
UNION: 例: SELECT UID AS ID ,Name AS NAME FROM user UNION SELECT CID AD ID, CNAME AS NAME FROM user2