如何通过以下图片更新表格?

时间:2017-04-27 06:40:35

标签: mysql sql

我想像

那样更新我的表格

关系A.id = B.a_id enter image description here

3 个答案:

答案 0 :(得分:2)

对于MySQL:

UPDATE B
JOIN A ON B.email = A.email
AND B.a_id = A.id
SET B.email = '';

UPDATE B
JOIN (
    SELECT * 
    FROM B
    GROUP BY email, a_id
    HAVING COUNT(*) > 1
) AS dp ON B.email = dp.email
AND B.a_id = dp.a_id
AND B.id != dp.id
SET B.email = '';

答案 1 :(得分:1)

第一种情况,表A中存在电子邮件:

update table_b b set email = '' where (select 1 from table_a a where a.email = b.email) = 1;

下一种情况,表B中的电子邮件重复:

update table_b b set email = '' where b.id in 
(select
    bb.id
    from table_b bb
    where bb.email in (
        select bbb.email,count(*)
        from table_b bbb
        where bbb.email = b.email
        having count(*) > 1
    ) 
    limit 1
)

答案 2 :(得分:1)

一个简单的inner join可以解决问题

UPDATE TableB
SET EMAIL='' --or set this to null 
FROM TableA
INNER JOIN TableB  ON
TableA.id = TableB.a_id AND
TableA.email = TableB.email

如果在同一个表中更新重复项,即表B,我会选择CTERow_number

WITH CTE AS(
   SELECT id,a_id,email,
       RN = ROW_NUMBER()OVER(PARTITION BY a_id,email ORDER BY id)
   FROM TableB
)
UPDATE  CTE SET email='' WHERE RN > 1