【问题标题】:Select and subselect UPDATE Mysql case disciplines x techniques选择和子选择 UPDATE Mysql 案例学科 x 技术
【发布时间】:2021-03-08 21:39:27
【问题描述】:

我有以下情况:我的表格“disciplines_units_technicians”包含以下列:

  • discipline_id;
  • unit_id;
  • 技术_id;

最初有两个单元,然后添加了第三个单元,这导致“UNITS X TECHNICAL”链接出现问题

我需要帮助进行以下更新:

首先我选择表格:

从学科_单位_技术人员那里选择学科_id?

我想选择 unit_id = 1、2 和 3 的返回值(1、2 和 3 的重复行),并从这个返回值中进行学科 ID 寄存器中的更新,其中:

更新学科_单位_技术人员 SET unit_id = '0' where unit_id = '2'

在哪里:

更新学科_单位_技术人员 SET unit_id = '2' where unit_id = '3'

只有在表中有 3 条记录的“discipline_id”id 中,它们包括 unit = 1、2 和 3,但我不知道如何在此进行更新的选择和子选择在这种情况下,不要 CONTEMPLATE 只对 unit = 1 和 2 重复返回的学科 ID,仅当在返回的学科 ID 中有一个单元 = 3 时。

示例,只需选择具有单元 1、2 和 3 的返回并进行必要的 pos 更新

【问题讨论】:

  • 我无法按照您的描述进行操作。请添加示例数据和所需的结果。
  • 修正你的问题:所以如果一个单一的学科ID有3个单位你想更新unit_id 2到0和3到2是你想要的吗?对于表中的所有学科 ID。对吗?
  • 我在说明中添加了一个示例,谢谢,

标签: mysql sql select sql-update inner-join


【解决方案1】:

先用这个脚本测试一下,看看输出是不是你想要的。

SELECT [discipline_id]
      , CASE WHEN [unit_id] = 2 THEN 0
             WHEN [unit_id] = 3 THEN 2
       ELSE [unit_id] END AS [unit_id]
      ,[technical_id]
FROM (
SELECT [discipline_id]
      ,[unit_id]
      ,[technical_id]   
      ,COUNT([discipline_id]) OVER(PARTITION BY [discipline_id]) AS [counter]
  FROM [Test].[dbo].[disciplines_units_technicians]
  GROUP BY [discipline_id]
          ,[unit_id]
          ,[technical_id]) A
          WHERE [counter] > 2

【讨论】:

    【解决方案2】:

    我认为这可以满足您的要求:

    update disciplines_units_technicians dut
    inner join (
        select discipline_id
        from disciplines_units_technicians
        where unit_id in (1, 2, 3)
        group by discipline_id
        having count(*) = 3
    ) dut1 on dut1.discipline_id = dut.discipline_id
    set dut.unit_id = case when dut.unit_id = 2 then 0 else 2 end
    where dut.unit_id in (2, 3)
    

    基本上,这会过滤具有所有 3 个unit_ids(1、2 和 3)的 discipline_ids 的表,并将 unit_id 2 更新为 0,并将 3 更新为 2。

    【讨论】:

    • 谢谢,这个合乎逻辑的解决方案真的可以按预期运行和工作
    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2019-04-03
    • 2021-03-27
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多