SQL - 增、改、删

发布于:2024-08-20 ⋅ 阅读:(112) ⋅ 点赞:(0)
  • 插入 (insert into)
    • 插入单行
      • insert into 表名 values ( 对应列的值,用','号间隔) //一般主键值用default,不可填null的不要填null
      • insert into 表名 (需要提供值的列名) values (与之对应的提供的值) //其他的值只需mysql默认提供
      • insert into 表名 子查询
        • 复制部分表信息,将部分表信息复制到另一个表中,这里就用选择语句当做子查询,将结果集复制到另一个表中
    • 插入多行
      • insert into shippers (name) values ('a1'),('a2'),('a3') //用','号间隔就能实现多行插入
    • 插入分层行
      • 如何往多表插入数据
      • 对一个表进行插入数据,通过MySQL内置功能 last_insert_id() 提供这个新生成的值,可以将相关的表中添加数据。
      • -- 多表插入数据
        insert into orders (customer_id,order_date)
        values ('1','2010-01-02');
        insert into order_items (order_id,product_id,quantity,unit_price)
        values (last_insert_id(),'1',2,2.2)

      • 创建表复制
        • create table order_archived as select * from orders //但是这样复制的表,MySQL会忽略一些属性如主键,自增等
        • -- 创建表复制
          create table order_archived as	
          select * from orders

      • 复制部分表信息
        • 将部分表信息复制到另一个表中,这里就用选择语句当做子查询,将结果集复制到另一个表中
        • -- 创建表复制部分表信息
          create table `invoices archive` as
          select invoice_id,number,c.name as client_id,invoice_total,payment_total
          invoice_date,due_date,payment_date
          from invoices i
          join clients c on i.client_id=c.client_id
          where payment_date is not null;
          -- 复制部分表信息
          insert into order_archived
          select * 
          from orders
          where order_date<'2019-01-01';

  • 更新(update)
    • 更新单行
      • update 表名 set 更改信息 where (确定哪行)
    • 更新多行
      • update 表名 set 更改信息 where (这个条件要更为通用,也就是可以指向多条记录)
    • 使用子查询
      • where client_id in (子查询返回结果集,可以是一个值,可以是一个字段的多个值,可以是多行记录)
      • -- 用子查询作为条件筛选
        update invoices
        set payment_total=invoice_total*0.5,
        payment_date='1111-01-01'
        where client_id in (
        select client_id 
        from clients
        where state in ('NY','CA'))

  • 删除(delete)
    • 删除行
      • delete from 表名 where (作为筛选条件,不加就删除表中所有记录)
      • 删除名字为'Myworks'的顾客的订单
        delete 
        from invoices
        where client_id in (
        select client_id 
        from clients
        where name='Myworks')


网站公告

今日签到

点亮在社区的每一天
去签到