根据另一列中的最小值更新重复记录

时间:2019-06-20 06:08:47

标签: mysql

我有一个表,其中包含两个字段:serial_id,product_id和is_original,重复产品

重复的记录具有相同的product_id(用户添加了相同的产品)。

我要执行的操作是根据最低的sequence_id填充“ is_original”列以0或1,并使用MASTER记录的重复sequence_id填充“ duplicate_products”(实际上,is_original = 1 )

示例输出:

--------------------------------------------------------------
sequential_id   product_id   is_original   duplicate_products
--------------------------------------------------------------
1                 123            1               3;6
2                 453            1               5
3                 123            0   
4                 332            1 
5                 453            0
6                 123            0

目前,我正在使用Redis和C#来确定重复项等其他解决方案。但是,如果可以使用SQL查询来完成,那就太好了

我尝试了以下操作,但收到“锁太多”错误

UPDATE tblproducts AS p 
JOIN (SELECT MIN(sequential_id) sequential_id, product_id 
FROM tblProducts GROUP BY product_id HAVING count(*) > 1) as m 
ON p.sequential_id = m.sequential_id SET p.is_original = '1';

2 个答案:

答案 0 :(得分:1)

结合表格和分组结果:

update tblproducts t
inner join (
  select 
    product_id, 
    min(sequential_id) sequential_id,
    concat(';', group_concat(sequential_id separator ';'), ';') dups
  from tblproducts
  group by product_id
) g on g.product_id = t.product_id
set 
  t.is_original = (t.sequential_id = g.sequential_id),
  t.duplicate_products = nullif(case
    when t.sequential_id = g.sequential_id then 
      trim(';' from replace(g.dups, concat(';', g.sequential_id, ';'), ''))
  end, '');

请参见demo
结果:

| sequential_id | product_id | is_original | duplicate_products |
| ------------- | ---------- | ----------- | ------------------ |
| 1             | 123        | 1           | 3;6                |
| 2             | 453        | 1           | 5                  |
| 3             | 123        | 0           |                    |
| 4             | 332        | 1           |                    |
| 5             | 453        | 0           |                    |
| 6             | 123        | 0           |                    |

答案 1 :(得分:0)

根据最低使用量将is_original更新为1或零

更新测试集Test.isoriginal_id = 5,其中sequence_id为(从选项卡中选择sequence_id(从test组按product_id选择test_id)作为选项卡);