表A(记录了用户和产品的关系):
userId        productId
  1              1
  1              2
  1              3
  2              4
  2              5
  3              2
现在我想把产品2合并到产品3中,合并过程:
对应每个和产品2有关系的用户(即上表中的用户1,3),若他和产品3有关系(即用户1),则把他和产品2的关系记录删除
若他和产品3没关系(即用户3),则把产品2替换成产品3.合并后的表:
userId        productId
  1              1
  1              3
  2              4
  2              5
  3              3可是不清楚sql语句怎么写呢?不一定用一句就完成。谢谢大家~~

解决方案 »

  1.   

    delete from table where f_prodctid in (select productid from table where f_productid = 2 and f_userid in (select f_userid from table where f_productid=3)set f_productid = 3 where f_productid = 2
      

  2.   

    delete from table where productId = 2 and userId in (select userId from table where productId=3);
      

  3.   

    楼主这样操作两个表合并我想应该有第三个表才行吧,两个表的话每个表的字段都不全,只有将两个表的信息联合查询之后插入到另个表(第三个表)中才行,也是一句SQL,不过需要另一个表来接应 
      

  4.   

    谢谢,可是执行是提示You can't specify target table 'table' for update in FROM clause 怎么回事呢?
      

  5.   

    表名正确么?你的表是table?不是A么?
      

  6.   

    表名我在这儿改成table了,没错。网上说不能在select时delete。。
      

  7.   

    1.delete from `表名` where productId = '2' and userId in (select userId from `表名` where productId='3');
    2.update `表名` set productId = '3' where productId = '2';就这两步就可以了
      

  8.   


    #首先建立零时表,在MySQL数据库中不能在对一张表做子查询的同时删除表中的数据 这样会有冲突 备份一张
    CREATE TABLE bak SELECT * FROM `表名`;
    #对应每个和产品2有关系的用户(即上表中的用户1,3),若他和产品3有关系(即用户1),则把他和产品2的关系记录删除
    delete from `表名` where pid = 2 and uid in (select uid from bak where pid = 3);
    #若他和产品3没关系(即用户3),则把产品2替换成产品3.
    #大哥 你这里说的'他' 意思是和12有关系但和3没有关系的吧 这个要说清楚 要不然别人把 2-4 2-5都更新2-3 2-3了
    update `表名` set pid = '3' where pid = '2'
    #删除零时表 
    drop table bak;
    #完事 基本上和楼上说的是一样的 你可以结贴了