1

我已经找到了与我所问的问题类似的问题的解决方案,但到目前为止还没有一个完全解决我的问题,所以如果有少量重复,请原谅我。

我有一个表 meta_data,其中包含列 project、stage、function、m_char_2 和 id

meta_data
project |  stage    |  function  | m_char_2  |  id     |
 519    | reception |    notes   |  11/1272  | 2363827 |
 519    | reception | diagnosis_1|           | 2363827 |
 519    | reception |    notes   |  11/1278  | 2370589 |
 519    | reception | diagnosis_1|           | 2370589 |
 519    | reception |    notes   |           | 2398654 |
 519    | reception | diagnosis_1|  13/2586  | 2398654 |

我希望将函数值 = 注释的 m_char_2 列中的值复制到相应 id 的函数值 = 诊断 1 的 m_char_2 列中。

我编写了一个语法,允许我对工作正常的单个 id 执行此操作

UPDATE meta_data 
SET m_char_2 =
  (SELECT m_char_2
   FROM (SELECT * FROM meta_data) AS md
   WHERE
     md.stage ='Reception'
     AND md.function='Notes'
     AND md.id = 2363827)
WHERE
  project=519
  AND stage='Reception'
  AND function ='Diagnosis_1'
  AND id = 2363827;

但是,我无法让它适用于多个 id。我有超过 100 条记录要更新,所以不必为每个 id 条目运行查询。

这不起作用:

UPDATE meta_data 
SET m_char_2 =
  (SELECT m_char_2
   FROM (SELECT * FROM meta_data) AS md
   WHERE
     md.stage ='Reception'
     AND md.function='Notes'
     AND md.id IN (2363827,2370589))
WHERE
  project=519
  AND stage='Reception'
  AND function ='Diagnosis_1'
  AND id IN (2363827,2370589);

它返回错误#1242 subquery returns more than 1 row

有什么建议么?

4

2 回答 2

2

在这里,我加入自己,并使用以下值meta_data更新所有行:diagnosis_1notes

UPDATE
  meta_data m1 inner join meta_data m2
  on m1.id=m2.id
     and m1.project=m2.project
     and m1.stage=m2.stage
     and m1.function='Notes'
     and m2.function='diagnosis_1'
SET
  m2.m_char_2=m1.m_char_2
WHERE
  m1.project=519
  AND m1.stage='Reception'
  AND m1.id IN (2363827,2370589);

(见这个小提琴)。如果您还需要保留现有值,例如“13/2586”,您可能需要添加一些其他条件,例如:

and (m2.m_char_2 IS NULL or LENGTH(m2.m_char_2)=0)
and m1.m_char_2 IS NOT NULL and LENGTH(m1.m_char_2)>0
于 2013-01-02T15:21:00.333 回答
1

只是为了好玩,我认为它不需要加入:

UPDATE meta_data AS mn
  SET m_char_2 = (
    SELECT m_char_2
    FROM (SELECT * FROM meta_data) AS md
    WHERE md.stage ='Reception' AND md.function='Notes'
      AND md.id = mn.id
    ) 
  WHERE project=519 AND stage='Reception'
    AND function ='Diagnosis_1' AND isnull(m_char_2)
于 2013-01-02T15:46:57.117 回答