©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
MySQL可以在一个SQL语句中更新多张表的记录,也可以通过多个表之间的关联关系更新某个表的数据。
假定目前有两张表goods
和goods_price
表,前者是保存商品的具体信息,后者是保存商品的价格,具体的表结构如下:
create table goods ( `id` int unsigned primary key auto_increment, `goods_name` varchar(30) not null default '', `deleted_at` int unsigned default null )engine innodb charset utf8; create table goods_price ( `goods_id` int unsigned not null, `price` decimal(8,2) not null default '0.00' )engine innodb charset utf8; insert into goods (id,goods_name) values (1,'商品1'),(2,'商品2'),(3,'商品3'),(4,'商品4'),(5,'商品5'); insert into goods_price values (1,'5.44'),(2,'3.22'),(3,'5.55'),(4,'0.00'),(5,'4.54');
将未删除的商品的价格*0.5,具体SQL语句如下:
UPDATE goods as g , goods_price as p SET p.price = p.price*0.5 WHERE p.goods_id = g.id AND g.deleted_at is null;
UPDATE goods g INNER JOIN goods_price p ON g.id=p.goods_id SET p.price=p.price*0.5 where g.deleted_at is null;
上面的更新语句使用另一个表的条件,更新一张表,也可以更新多个表。具体SQL语句如下:
UPDATE goods g INNER JOIN goods_price p on g.id=p.goods_id set p.price=p.price*0.5,g.deleted_at=unix_timestamp(now()) where g.is_deleted_at is null;