MySQL学习笔记(18)——多表更新、连接
前置工作
新建一张物品类别表:
CREATE TABLE IF NOT EXISTS tdb_goods_cates
(
cate_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
cate_name VARCHAR(40) NOT NULL
);
从tdb_goods表中查出所有类别:
SELECT goods_cate FROM tdb_goods GROUP BY goods_cate;
使用INSERT tb_name SELECT …添加记录:
INSERT tdb_goods_cates(cate_name) SELECT goods_cate FROM tdb_goods GROUP BY goods_cate;
于是,tdb_goods_cates数据如下:
多表更新
参照另外的表来对本表的更新。
UPDATE table_references
SET col_name1={expr1 | DEFAULT}
[, col_name2={expr2 | DEFAULT}] …
[WHERE where_condition]
连接
MySQL在SELECT语句、多表更新、多表删除语句中支持JOIN操作。
连接类型:
- inner join,内连接
在mysql,join,cross join和inner join 是等价的。 - left [outer] join,左外连接
- right [outer] join,右外连接
语法结构:
table_references {[INNER | CROSS] JOIN | {LEFT | RIGHT} [OUTER] JOIN} table_reference ON conditional_expr
demo:
UPDATE tdb_goods INNER JOIN tdb_goods_cates ON goods_cate=cate_name SET goods_cate=cate_id;
参照tdb_goods_cates表的cate_name来修改tdb_goods的goods_cate。
CREATE … SELECT
创建数据表通知书将查询结果写入到数据表
CREATE TABLE [IF NOT EXISTS] tb_name
[(create_definition,…)]
select_statement
demo:
目标:把tdb_goods的brand_name参照tdb_goods_brands表更新成ID形式
tdb_goods_brands表,创建:
CREATE TABLE tdb_goods_brands
(
brand_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
brand_name VARCHAR(40) NOT NULL
)
SELECT brand_name FROM tdb_goods GROUP BY brand_name;
- SELECT * FROM tddb_goods_brands;
- UPDATE tdb_goods AS g INNER JOIN tdb_goods_brands AS b ON g.brand_name=b.brand_name SET g.brand_name=b.brand_id;
PS:记得修改列的数据类型来减少字节数的使用。
ALTER TABLE tdb_goods
CHANGE goods_cate cate_id SMALLINT UNSIGNED NOT NULL,
CHANGE brand_name brand_id SMALLINT UNSIGNED NOT NULL;