简体   繁体   English

SQL Update如果已经存在,则插入

[英]SQL Update if already exists, else insert

I have the following sql statement: 我有以下sql语句:

$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id, 
                  code, size, details, color, top, price) 
        VALUES ('$variant_id', '$global_variant_id', '$code', '$size', 
                '$details', '$color', '$top', '$price')";

This is just a basic INSERT sql. 这只是一个基本的INSERT sql。 Is there a way for it to Update a record if the 'variant_id' is already present. 如果'variant_id'已经存在,有没有办法让它更新记录。 If the 'variant_id' is not already there it should Insert a new one. 如果'variant_id'尚未存在,则应插入一个新的。

Any help would be appreciated 任何帮助,将不胜感激

$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id, 
                  code, size, details, color, top, price) 
        VALUES ('$variant_id', '$global_variant_id', '$code', '$size', 
                '$details', '$color', '$top', '$price')
        ON DUPLICATE KEY UPDATE
          global_variant_id = VALUES(global_variant_id),
          code = VALUES(code),
          size = VALUES(size),
          details = VALUES(details),
          color = VALUES(color),
          top = VALUES(top),
          price = VALUES(price)";

In MySQL you can use ON DUPLICATE KEY 在MySQL中,您可以使用ON DUPLICATE KEY

INSERT INTO jos_vm_product_details (variant_id, global_variant_id, 
                  code, size, details, color, top, price) 
        VALUES ('$variant_id', '$global_variant_id', '$code', '$size', 
                '$details', '$color', '$top', '$price')";

ON DUPLICATE KEY UPDATE `code`=VALUES(`code`);

In T-SQL (2008 an higher) you could use MERGE 在T-SQL(2008更高版本)中,您可以使用MERGE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM