您的位置:首页 > 教育 > 培训 > SQL - 增、改、删

SQL - 增、改、删

2024/10/5 19:16:46 来源:https://blog.csdn.net/m0_74403543/article/details/141297568  浏览:    关键词:SQL - 增、改、删
  • 插入 (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')

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com