04-增删查改数据表
添加数据
1
| insert into 表名 [(字段名 [,字段名] ...)] values (值的列表)
|
插入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| insert into demo.goodsmaster2 ( itemnumber, barcode, goodsname, specification, uint, price )values ( 4, '0003', '尺子', '三角型', '把', 5 );
|

只给三个字段
1 2 3 4 5 6 7 8 9 10 11 12 13
| INSERT INTO demo.goodsmaster ( -- 这里只给3个字段赋值,itemnumber、specification、unit不赋值 barcode, goodsname, price ) VALUES ( '0004', '测试', 10 );
|

插入数据记录时,必须考虑的三种字段约束
- 字段允许为空,赋值时可以为空值
- 字段是主键,不能为空
- 字段定义不能为空,且不是主键,就必须按照添加的约束进行处理
尝试将specification
改为不能为空
1 2
| ALTER TABLE demo.goodsmaster MODIFY specification TEXT NOT NULL;
|
报错:

因为有部分数据的specification
是null,所以不能修改,除非删除null数据
插入查询结果
1 2 3 4
| insert into 表名 select 字段名或值 from 表名 where 条件
|
删除数据
为了防止误删,习惯性添加where
语句
删除所有数据
1 2
| delete from demo.goodsmaster where itemnumber > 1;
|
修改数据
1 2 3
| update 表名 set 字段名=值 where 条件
|
注意:不要修改主键字段的值
修改主键字段的值会有怎样的结果?

1 2 3
| update demo.goodsmaster set itemnumber = 10 where itemnumber = 3;
|

找不到原来的数据了

查询数据
1 2 3 4 5 6 7
| select *|字段列表 from 数据源 where 条件 group by 字段 having 条件 order by 字段 limit 起始点,行数
|
select
:查询关键字 ,*
是通配符,查询所有字段
where
:查询条件
group by
:查询结果如何分组,经常与Mysql的聚合函数一起使用
having
:筛选查询结果,跟where
类似
FROM
FROM关键字表示查询的数据源,数据源不一定是表,也可以是查询结果
1 2 3 4 5
| select a.goodsname,a.price from( select * from demo.goodsmaster )as a;
|

红色框里的部分叫做派生表(derived table)或者自查询(subquery)
ORDER BY
ASC表示生序,DESC表示降序
1 2 3
| select * from demo.goodsmaster order by barcode ASC,price DESC;
|
不加order,查询

加order,查询

LIMIT
1 2 3
| select * from demo.goodsmaster limit 1,2
|
起始位2,结束为3

处理重复信息
将B的数据插入A中,解决重复信息
1 2 3 4
| insert into demo.goodsmaster select * from demo.goodsmaster2 as a on duplicate key update barcode = a.barcode,goodsname=a.goodsname;
|
表A

表B

