51Testing软件测试论坛

标题: 基于mysql数据库的基础知识二 [打印本页]

作者: 测试积点老人    时间: 2018-12-14 16:58
标题: 基于mysql数据库的基础知识二
约束


···························

1.主键约束 PRIMARYKEY
每张数据表只能 存在一个主键
主键保证记录的唯一性
主键自动为 NOT NULL


添加主键约束

如:ALTER TABLE persion(数据表名称) ADD CONSTRAINTPK_persion_id(系统自动生成的主键id名字、格式) PRIMARY KEY (id);

删除:persionDROP PRIMARY KEY;
···························

保证数据完整性,一致性

表极约束:两个字段以上, 列极约束:某个字段

···························

2.外键约束 FOREIGNKEY



这个是干嘛的呢??????

  FOREIGN KEY (pid子表id) REFERENCESpersion父表(id);

可以:pid SMALLINT UNSIGNED


添加约束外键

如:ALTER TABLE persion(数据表名称) ADD FOREIGNKEY(子表id) REFERENCES persion父表(id)

删除:··················


3.添加唯一约束

如:ALTER TABLE persion(数据表名称) ADDUNIQUE(username1,username2,...);

删除:ALTER TABLE persion DROP INDEXusername;


4.添加/删除默认约束

如:ALTER TABLE persion(数据表名称) SET/DROPDEFAULT

··································

子查询



SELECT ROUND(ANG(goods_price),2) FROM tdb_goods;

子查询:

SELECT goods_id,goods_name,goods_price FROM tdb_goods WHEREgoods_price>=平均值

当使用自查询返回多个结果是要使用:AND,SOME,ALL连接语句

把查询到的记录插入到别的表中

INSERT tdb_goods_cates(cate_name) SELECT goods_cate FROM tdb_goodsGROUP BY tdb_cates;

···············································

连接

tbl_name  [[AS] alias] table_subquery [AS]alias

数据表中赋予别名tbl_name AS name_alias

在子查询中子表就一定要赋予别名

连接类型

内连接 INNER   仅符合表连接的条件

左外连接  LEFT [OUTER]JOIN

右外连接  RIGHT [OUTER]JOIN

使用ON关键来设定连接条件,也可以使用WHERE来代替,过滤


1.内连接

SELECT goods_id,goods_name,cate_name  FROMtdb_goods  INNER JOIN tdb_goods_cates  ON tdb_goods.cate_id=tdb_goods_cates.cate_id;


2.外连接

SELECT goods_id,goods_name,cate_name  FROMtdb_goods  LEFT JOIN tdb_goods_cates  ON tdb_goods.cate_id=tdb_goods_cates.cate_id;

SELECT goods_id,goods_name,cate_name  FROMtdb_goods  RIGHT JOIN tdb_goods_cates  ON tdb_goods.cate_id=tdb_goods_cates.cate_id;


多表连接

SELECT goods_id,goods_name,goods_price,cate_name,brand_name FROMtdb_goods AS g

INNER JOIN tdb_goods_cates AS c ON g.cates_id=b.cates_id

INNER JOIN tdb_goods_brands AS b ONg.brand_id=b.brands_id


无限分类表设计
自身连接
父类--子类
SELECT s.type_id,s.type_name,p.type_name FROM tdb_good INNER JOINtdb_goods_type AS p ON s.parent_id=p.type_id;

父类--子类
多表删除
DELETE  t1FROM tdb_goods AS t1 LEFTJOIN

(SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_nameHAVING count(goods_name)>=2) AS t2 ON  t1.goods_name=t2.goods_name

WHERE t1.goods_id>t2.goods_id;

SELECT goods_id,goods_name FROM tdb_goods GROUP BY tdb_goods_nameHAVING count(goods_name)>=2;






欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2