【问题标题】:How to update column in a table from another table based on condition?如何根据条件从另一个表中更新表中的列?
【发布时间】:2012-09-11 05:04:51
【问题描述】:

我有两张桌子

  1. 它包含的学生表(Student_id,school_code,name,year,...)
  2. 它包含的学校表(school_id,School_code,School_name,year 等等……)

我想根据学校代码和年份将学生表中的 school_code 列更新为学校代码表中的 school_id 列。我有五年的数据。所以 school_id 每年都不同。

我的查询是

UPDATE Master.Student
   SET school_code=( select school_id from Master.school as sc
  JOIN master.student as st
    ON st.school_code=sc.school_code
 WHERE sc.year=x)
 WHERE st.year=x;

但它没有更新。我收到subquery returns more than one value 的错误。

【问题讨论】:

  • 这是因为您获得了多个schoo_id 的值。并显示您的完整错误。
  • 给定的答案对您没有帮助吗?
  • 对不起...我的问题解决了...谢谢大家

标签: sql-server subquery sql-update multiple-tables


【解决方案1】:

既然可以直接使用子查询,为什么还要使用?

UPDATE st
  SET st.school_code = sc.school_id 
FROM master.student AS st
  JOIN Master.school AS sc
ON st.school_code = sc.school_code
WHERE sc.year=x
  AND st.year=x;

更多信息见UPDATE (Transact-SQL)

【讨论】:

    【解决方案2】:
    UPDATE Master.Student
      SET school_code = sc.school_id 
    FROM Master.school as sc
    WHERE school_code = sc.school_code
      AND year = x
      AND st.year = x;
    

    【讨论】:

    • 你可以在 FROM 子句中使用 吗?整洁的!这是否记录在某处?
    【解决方案3】:

    试试这个查询

    UPDATE student SET school_code = c.school_id  
    FROM student t
      INNER JOIN school c 
        ON t.school_code = c.school_code AND t.year = c.year
    WHERE c.year=x
    

    【讨论】:

      【解决方案4】:
      Update Table B set column name (of table b) =x.column name (from Table A) from    
      (    
      Select column name from Table A a,Table B b    
      where a.Column name=b.column name            
      )x    
      where Table b.Column name=x.Column name(of Table b)
      

      【讨论】:

      • 你为什么使用旧式连接语法?另外,您为什么不使用问题中的两个表和列?
      猜你喜欢
      • 2022-11-10
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多