Node学习(六)03-SQL语句——添加数据insert into、修改数据update、删除数据delete from、连接查询select * from之内连接、左连接、右连接和定义别名

5. 添加数据

方式一:指定字段和值,只要字段和值对应即可。和字段的顺序无关

-- insert into 表名 (字段, 字段, ...) values (值, 值, ....)
insert into heroes (name, nickname) values ('孙悟空', '齐天大圣')

效果

postgres insert into select字段顺序不一样 insert into select from字段顺序_连接查询

方式二:和顺序有关,因为没指定字段,所以值必须是所有的值,而且顺序和表中字段的顺序要一致

-- 添加所有字段的时候,字段可以省略;而且添加的时候,字段的顺序要和创建表时的字段顺序一致
insert into heroes values (null, '卡特琳娜', '不祥之刃', null, '转圈圈', 23, '女')

效果

postgres insert into select字段顺序不一样 insert into select from字段顺序_字段_02

方式三:使用set里设置新数据的值,没有顺序关系

-- insert into heroes set 字段=值, 字段=值,....
insert into heroes set nickname='战争女神', name='希维尔', skill='扔圈圈'

效果

postgres insert into select字段顺序不一样 insert into select from字段顺序_数据库_03

推荐使用顺序:方式三>方式一>方式二

6. 修改数据

格式:

update 表名 set 字段1=值1, 字段2=值2,… where 修改条件

修改表中的哪一条(几条)数据的 字段1=值1…

不指定修改条件会修改所有的数据

-- update 表名 set 字段=值, 字段=值... where 修改条件

-- 修改id为27的英雄的技能
update heroes set skill='在空中转圈圈' where id=27

-- 没有条件,将会修改全部的数据,非常危险
update heroes set skill='在空中转圈圈'

效果

postgres insert into select字段顺序不一样 insert into select from字段顺序_学习_04

7. 删除数据

格式: delete from 表名 where 删除条件

注意:不指定条件将删除所有数据

-- delete from 表名 where 条件
-- 删除id为27的英雄
delete from heroes where id=27

-- 没有条件,删除所有的数据
delete from heroes

drop table heroes; – 删除stu表

drop database yingxiong – 删除库

效果1-删除单条sql

postgres insert into select字段顺序不一样 insert into select from字段顺序_连接查询_05

效果2-删除所有sql(清空)

postgres insert into select字段顺序不一样 insert into select from字段顺序_字段_06

8. 连接查询

连接查询意思是将两个表或更多张表连接到一起查询。查询的结果一般会包含有两个表的全部结果。

不是说任意的两个表都可以连接查询;能够连接查询的两个表必须有关系才行。

连接查询的语法:

select * from 表1 连接 表2 on 两个表的关系 [连接 表3 on 关系 ....]

-- select * from 表1 连接 表2 on 关系
-- 内连接
select * from boy join girl on boy.flower = girl.flower
-- 左连接
select * from boy left join girl on boy.flower = girl.flower
-- 右连接
select * from boy right join girl on boy.flower = girl.flower

-- 
-- 定义别名
-- 假设boy表别名为b;girl表别名为g
select b.name bname, b.flower bflower, g.name gname, g.flower gflower
 from boy b join girl g on b.flower = g.flower

1-sql表内连接查询

postgres insert into select字段顺序不一样 insert into select from字段顺序_连接查询_07

2-左连接

postgres insert into select字段顺序不一样 insert into select from字段顺序_数据库_08

3-右连接

postgres insert into select字段顺序不一样 insert into select from字段顺序_学习_09

4-定义别名

postgres insert into select字段顺序不一样 insert into select from字段顺序_学习_10

小结:

  • 查询
  • select * from heroes [where …] [order by …] [limit …]
  • 添加
  • insert into heroes (字段, 字段, …) values (值, 值)
  • insert into heroes set 字段=值, 字段=值, …
  • 修改
  • update heroes set 字段=值, 字段=值, … where 条件
  • 删除
  • delete from heroes where 条件