Select 并子选择 UPDATE Mysql 个案学科 x 技术

Select and subselect UPDATE Mysql case disciplines x techniques

我有以下情况:我有 table“disciplines_units_technicians”,其中包含以下列:

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

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

首先我select table:

SELECT discipline_id 来自 disciplines_units_technicians 哪里?

我想 SELECT returns(1、2 和 3 的重复行),其中 unit_id = 1、2 和 3 并从此 return 在 discipline_id 寄存器中进行更新,其中:

更新 disciplines_units_technicians 设置 unit_id = '0' 其中 unit_id = '2'

以及地点:

更新 disciplines_units_technicians 设置 unit_id = '2' 其中 unit_id = '3'

只有在 table 中有 3 条记录的“discipline_id”id,也就是说,它们包括 unit = 1、2 和 3,但我不知道如何在这种情况下制作一个 select 和一个 subselect 用于更新,不要考虑 discipline_id returns 仅对单元 = 1 和 2 进行重复,仅当有discipline_id.

中的return中的unit=3

示例,仅 select return 具有单元 1、2 和 3 并且需要进行位置更新

我认为这符合您的要求:

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)

基本上,这会过滤 discipline_id 的 table,其中包含所有 3 个 unit_id(1、2 和 3),并将 unit_id 2 更新为 0,和 3 比 2。

首先使用此脚本进行测试,看看输出是否符合您的要求。

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