zoukankan      html  css  js  c++  java
  • SQL基础(二)-- 多张表Update语法

    一、当用一个表中的数据来更新另外一个表中的数据时(两张表要有关联):

           1.  update  t1  set  t1.c2 =  t2.c2 

                from   t2  where  t1.c1 =  t2.c1

           2.  update  t1  set  t1.c2  =  t2.c2

                from  t1  inner  join  t2  on  t1.c1  = t2.c1

     二、From子句中指定的表的别名不能作为Set column_name子句中被修改的字段的限定符使用

            UPDATE titles
            SET t.ytd_sales = t.ytd_sales + s.qty
            FROM titles t, sales s
            WHERE t.title_id = s.title_id
                 AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

            若要使上例合法,请从列名中删除别名 t 或使用本身的表名。

            UPDATE titles
            SET ytd_sales = t.ytd_sales + s.qty
            FROM titles t, sales s
            WHERE t.title_id = s.title_id
                 AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

    更新一列:

    update mytab a set name=(select b.name from goal b where b.id=a.id)

    where exists (select 1 from goal b where b.id=a.id);

    更新多列:

    update mytab a 

    set (name,address)=(select b.name,b.address 

    from goal b 

    where b.id=a.id)

    where exists (select 1 

    from goal b

    where b.id=a.id )

    特别是要注意exists后面的语句:)这会让目标行不至于为NULL

     

    更新update多个关联表的SQL写法:
    update customers a
    set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
    where exists (select 1
    from tmp_cust_city b
    where b.customer_id=a.customer_id
    )
    update 超过2个值
    update customers a
    set (city_name,customer_type)=(select b.city_name,b.customer_type
    from tmp_cust_city b
    where b.customer_id=a.customer_id)
    where exists (select 1
    from tmp_cust_city b
    where b.customer_id=a.customer_id
    )

     --另一种修改形式
    UPDATE SO_Item SET SO_Item.Quantity=Quantity-(SELECT SUM(Quantity) FROM @SaleRule_ItemList AS Rule_Item WHERE Rule_Item.ProductSysno=SO_Item.ProductSysno)
    FROM @SO_ItemList AS SO_Item 
    WHERE SO_Item.ProductSysno IN (SELECT ProductSysno FROM @SaleRule_ItemList)
  • 相关阅读:
    ostringstream的使用方法
    《算法导论》为什么经典
    JAVA数组的定义及用法
    具体解释Android中AsyncTask的使用
    POJ 1207 The 3n + 1 problem
    图像切割之(五)活动轮廓模型之Snake模型简单介绍
    RapeLay(电车之狼R)的结局介绍 (隐藏结局攻略)
    线程安全和线程不安全理解
    atitit...触发器机制 ltrigger mechanism sumup .的总结O8f
    winrar3.7-winrar4.0的注冊码
  • 原文地址:https://www.cnblogs.com/BounceGuo/p/10234114.html
Copyright © 2011-2022 走看看