使用MySQL更新具有条件和ID的表中的表

时间:2018-03-22 04:00:39

标签: mysql mysql-workbench

我有005_my_sc表,列

pdb_id  listing_type
1       new
2       sale
3       rent

我也有005_my_cl表,列

pdb_id  listing_type
1       0
2       0
3       0

我想用以下条件更新005_my_cl表

  • 005_my_sc ID匹配005_my_cl ID
  • 如果005_my_sc中的listing_type ='new'=> listing_type in 005_my_cl = 2
  • 如果005_my_sc中的listing_type ='rent'=> listing_type在005_my_cl = 1
  • 如果005_my_sc中的listing_type ='sale'=> listing_type in 005_my_cl = 2

这是我正在尝试的:

update 005_my_sc old, 005_my_cl new1 
set new1.listing_type = 2 
where old.pdb_id = new1.pdb_id and old.listing_type = 'new'

代码没有语法错误,但没有任何改变,我错过了什么???

1 个答案:

答案 0 :(得分:1)

你可以试试这个,交配:

UPDATE 005_my_sc t1
    INNER JOIN 005_my_cl t2 ON t2.pdb_id = t1.pdb_id
SET t2.listing_type = (
    CASE t1.listing_type
        WHEN 'new' THEN 2
        WHEN 'rent' THEN 1
        WHEN 'sale' THEN 2
    END
)
WHERE t1.listing_type IN ('new', 'rent', 'sale');

也许你错过了这些物品

  • 更新时,您可以使用任何类型的JOIN
  • 不是('new','rent','sale')列表类型的默认值,因此您不再需要此行WHERE t1.listing_type IN ('new', 'rent', 'sale')

考虑到您有默认值,您可以改用:

UPDATE 005_my_sc t1
    INNER JOIN 005_my_cl t2 ON t2.pdb_id = t1.pdb_id
SET t2.listing_type = (
    CASE t1.listing_type
        WHEN 'new' THEN 2
        WHEN 'rent' THEN 1
        WHEN 'sale' THEN 2
        ELSE 2
    END
);