简体   繁体   English

根据表1中的条件将SQL更新表(1)转换为另一个表中的值

[英]SQL Update table(1) to values from another, based on conditions within Table 1

I'm trying to create a sort of conversion tool that will update a set of data with new values based on certain conditions. 我正在尝试创建一种转换工具,该工具将根据特定条件使用新值更新一组数据。

Table A has columns Scheme1, Class1, Condition 1, Condition 2, 表A的列为Scheme1,Class1,条件1,条件2,

Table B has a list of all possible Scheme(s)2, Class(s)2 that I need to update to. 表B列出了我需要更新为所有可能的Scheme2,Class2的列表。

Basically, everything in Table A sets the conditions for what needs to be updated. 基本上,表A中的所有内容都为需要更新的内容设置了条件。 Which is where I'm having difficulty. 这是我遇到的困难。

I was planning something along the lines of 我正在按照

UPDATE table_A
SET class1 = table_B.class '1'
WHERE IN (class1= '1', condition1 = '1', condition2 = '2')

then repeating this for all classifications. 然后针对所有分类重复此操作。 There's about 50 classifications. 大约有50个分类。

Is this on the right track, or is there a quicker/cleaner way to do this? 这是在正确的轨道上吗,还是有更快/更清洁的方法来做到这一点? Do I even need the second table or can I just update it in line? 我是否还需要第二张表,或者可以直接更新它? Would it be easier to just create a 3rd instead of updating the original table? 仅创建第3个而不是更新原始表会更容易吗? (I need to move this data outside of SQL after the conversion) (转换后,我需要将此数据移到SQL之外)

If I understand you correctly, this should work 如果我对您的理解正确,那应该可以

UPDATE a
SET class1 = b.class
FROM
    TableA a
    JOIN TableB b ON a.scheme = b.scheme
WHERE
    a.condition1=...
    AND a.condition2 = ...

Approach the development of UPDATE statements from a SELECT first perspective, then once you can retrieve the values the way you want them, convert the select into an UPDATE. 首先从SELECT的角度着手开发UPDATE语句,然后以所需的方式检索值后,将select转换为UPDATE。

First build a SELECT to visualize the results. 首先构建一个SELECT以可视化结果。 Update what with what with what . 什么更新什么

SELECT a.class1
       b.class1
FROM table_A AS a
  INNER JOIN table_B AS b
    ON a.id = b.id
WHERE a.condition1 = '1'

Now you can modify that to an UPDATE. 现在,您可以将其修改为UPDATE。

--SELECT a.class1
--       b.class1
UPDATE a
SET a.class1 = b.class1
FROM table_A AS a
  INNER JOIN table_B AS b
    ON a.id = b.id
WHERE a.condition1 = '1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM