创建数据库:
主键: unsigned primary key auto_increment
外键: foreign key(xx) references table_name(xx)
字段:
类型: int ; tinyint ;char(20);varchar(255); date; datetime; text; float(5,2); double(10,2); long; decimal(15,10)
约束:primary key; foreign key; not null; unique; unsigned; default; check
备注: comment ‘xxxxx’
- create table my_tab (
- id int unsigned primary key auto_increment
- username varchar(20) not null unique comment '用户名',
- age int CHECK (age > 0 AND age <= 200)
- gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
- image varchar(300)
- entrydate date
- column1 int,
- column2 int,
- CONSTRAINT fk_example1 FOREIGN KEY (column1) REFERENCES ref_table1(ref_column1),
- CONSTRAINT fk_example2 FOREIGN KEY (column2) REFERENCES ref_table2(ref_column2),
- ) comment '表';
复制代码 表字段增删改:
- alter table tbname add qq varchar(11) comment 'QQ号码';
- alter table tbname modify qq varchar(13) comment 'QQ号码';
- alter table tbname change qq qq_num varchar(13) comment 'QQ号码';
- alter table tbname drop qq;
- rename table tbname to newtbname;
复制代码 数据增删改查:
增: insert into table(…) value(…)
删: delete from table where(and ; or ; not ; is null)
改: update tabname set … where …
查: select [distinct] … from where(条件) … group by(分组)… having…(分组后条件)… order by(排序asc desc) … limit(分页索引起始,查询总条数) …
- insert into tbname(name, age) values ('张无忌', 10);
- insert into tbname values('a',1),('b',2)...
- delete from tabname
- delete from tabname where not age=1
- delete from tabname where age=1 and name!='a'
- delete from tabname where (age=1 and name!='a') or name='c'
- update tabname set area='wuhan',emp='fengxing'
- update tabname set age=25,phone=123 where name='a'
- select age from tb where area='wuhan'
- select name,age,area from tb where name like '熊_龙%'
- //聚合函数 count max min avg sum
- select count(*) from tb where name like '%龙%'
- select max(age) from tb
- //分地区统计总数,年龄低于30,按照年龄分组,总数大于1个的,增序显示前3条数
- SELECT age,area,count(*) FROM test WHERE age<30 GROUP BY age,area ORDER BY age ASC,area DESC LIMIT 100
- //解析如下,按年龄地区统计总数,group by代表每行是一个满足条件(age<30)的聚合,优先按照age增序,area降序排列,显示100条:
- //切记 select超过一个以上的列时如age,area,所有的列必须包含在group by 中,select查询的列应该是group by的子集,否则语意上有冲突,分组会出现分歧,比如使用group by age,按照age分组,但是你要求显示area列,那这个聚合可能有wuhan hangzhou shanghai,数据库不可能显示成
- // 18 wuhan,hangzhou,shanghai 32
- //另外select必须有一个显示的列,不能是*,group by还需要筛选的可以在后面添加 having count(*)>5 / area!=shanghai 这种条件,对聚合后的列进行二次筛选,order by当然也必须要是group by内的列
- 函数和group by时配套使用的,
- age 地区 count(*)
- 18 wuhan 3
- 18 shanghai 9
- 18 hangzhou 6
- 19 wuhan 5
- 21 shanghai 7
- 21 hangzhou 2
- 26 hangzhou 8
- 29 shanghai 12
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |