一、DDL语法:
1. 创建表:
- 分区表:
/*!scadb:partitionkey=id rule=rule10*/CREATE TABLE `a` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`t` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ;
/*!scadb:partitionkey=id rule=rule10*/CREATE TABLE if not exists `b` (
id bigint(20) NOT NULL,
tid bigint(20) NOT NULL,
address varchar(50) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (id, tid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ;
- 非分区表:
CREATE TABLE t (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`t` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ;
2. 删除表
drop table a ;
drop table if exists a ;
3. 修改表
alter table a add key (name) ;
alter table a drop key name;
alter table a add column k int ;
二、DML语法:
插入:
insert into a ( id, name, t ) values ( 1 , '123', now()) ;
insert into a ( name, t ) values ( '234', now()) ;
insert into a ( id, name, t) values ( 1,'555',now()) on duplicate key update name='555', t = now() ;
更新:
update a set name='444' where id = 1 ;
update a set name='444' where id = 1 and t < now() ;
update b set address='33' where id=1 ;
删除:
delete from a where id = 1 ;
delete from a where id =1 and t < now() ;
替换:
replace into a ( id,name,t ) values ( 1,'34', now()) ;
三、查询语法:
基于分区键的查询:
select * from a where id = 1 ;
select * from a where id in ( 1,2,3,4,5,6) ;
select * from a where id = 1 and t < now() ;
不基于分区键的查询:
select id,name from a where name ='123' order by id limit 20 ;
* 必须带limit,select 后面不能用*号。
select name,count(*),avg(id) from a group by name order by name ;
* 有group by不必带limit
四、其他语法
1、显示数据库:
show databases ;
目前系统中永远只有一个数据库:scadb
2、显示表:
show tables ;
3、显示创建表的语法:
show create table a ;
4、查询系统变量
select 1, last_insert_id() , @@autocommit;