插入数据
1.INSERT tbl_name VALUES(值1,值二,值三,表达式1,……)[,(值1,值二,值三,……)] 可以同时插入多条记录,但不能使用子查询,记录的值可以是值,也可以是表达式(不加单引号) 2.INSERT tbl_name SET col_name1=值1,col_name2=值2 只能一次性插入一条记录,但可以使用子查询subquery 例:INSERT users SET username='Ben',password='456';修改数据
UPDATE [LOW_PRIORITY] [IGNORE] table_reference SET col_name1={expr1|DEFAULT} [,col_name2={expr2|DEFAULT}]... [WHERE where_condition] 如果省略WHERE条件的话,则字段下的所有数据将全部被修改 修改多列: UPDATE users SET age = age - id,sex = 0; UPDATE users SET age= age + 5; ------将字段中age全部加5,更新多个字段以逗号分隔。 UPDATE users SET age= age +10 WHERE id % 2 =0; -----将偶数列的ID年龄加10(id与2取余为0)删除数据
1、删除记录DELETE:分为单表删除和多表删除 2、单表删除:DELETE FROM tbl_name [WHERE where_conditon]; 例:DELETE FROM tbl_name WHERE id = 6; 3、若不添加WHERE则删除【全部记录】 删除后再插入,插入的记录中设置为AUTO_INCREMENT(自动编号)列将从最大值往上加,而不是填补删除的。单表查询
SELECT id,username FROM users WHERE age>18 GROUP BY sex HAVING count(username)>2 /*having的条件必须是函数或者查询中的列*/ ORDER BY id DESC LIMIT (4,100) /*从第五条数据开始查起 总共查询100条数据*/将一张表中的数据插入到另一张中
INSERT tbd_goods_brand(brand_name) SELECT good_brand FROM tbd_goods GROUP BY goods_brand;使用一张表中的数据修改另一张表中的数据
UPDATE tbd_goods AS g INNER JOIN tbd_goods_brand AS gb ON g.goods_brand = gb.brand_name SET g.goods_brand = gb.brand_id;多表更新一步到位
CREATE TABLE goods_brand( brand_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, brand_name VARCHAR(20) NOT NULL ) SELECT brand_name FROM tbd_goods GROUP BY brand_name; UPDATE tbd_goods AS g INNER JOIN tbd_goods_brand AS gb ON g.goods_brand = gb.brand_name SET g.goods_brand = gb.brand_id; ALTER TABLE tbd_goods CHANGE goods_cates cate_id SMALLINT NOT NULL UNSIGNED, CHANGE goods_brands brand_id SMALLINT NOT NULL UNSIGNED;