简体   繁体   English

MySql Update if if exists如果不存在则插入

[英]MySql Update if exists insert if not

I'm trying to insert new to the table or to update the previous one in the same query.I can solve it with a bit of php code but my goal is to make it all in sql. 我试图在表中插入新的或在同一个查询中更新前一个。我可以用一些PHP代码来解决它,但我的目标是在sql中完成所有操作。

The problem 问题

My app has names in different languages, I can add new languages to it.When i add new languages the translations for my products raise. 我的应用程序有不同语言的名称,我可以添加新语言。当我添加新语言时,我的产品的翻译会提高。 My goal is to send the script information ,and if two columns are same than the data should be updated, but if they are not they should be updated. 我的目标是发送脚本信息,如果两列相同,则应更新数据,但如果不是,则应更新。

Here is some of my query: 以下是我的一些疑问:

"INSERT INTO product_name(link,product_id,language)
VALUES(:link,:product_id,:language) ON DUPLICATE KEY UPDATE
link=:link,product_id=:product_id,language=:language"

This query above solves one portion of the problem, but when i want to change the link it adds new data.My goal is to change the link ,and if the product_id and language are same in that row than it should be updated,if not than a new one shall be added.Unique wont solve the problem since i need to use same languages and id's in the table. 上面的查询解决了问题的一部分,但是当我想更改链接时,它会添加新数据。我的目标是更改链接,如果该行中的product_id和语言相同,则应该更新,如果不是因为我需要在表格中使用相同的语言和id,所以不应该添加新的。

I think you just need a unique constraint on (product_id, language) -- and no unique constraint or primary key on all three columns. 我认为你只需要(product_id, language)唯一约束 - 并且在所有三列上都没有唯一约束或主键。

CREATE UNIQUE INDEX unq_productname_product_language ON product_name(product_id, language);

This requires that the pair of values be unique, not each one individually. 这要求这值是唯一的,而不是每个值都是唯一的。

Then this should do what you want: 那么这应该做你想要的:

INSERT INTO product_name(link, product_id, language)
    VALUES (:link, :product_id, :language)
    ON DUPLICATE KEY UPDATE link = VALUES(link);

Notice that this version uses VALUES(link) . 请注意,此版本使用VALUES(link) This uses the value being inserted in the statement. 这使用在语句中插入的值。 I think that is clearer than repeating the expression. 我认为这比重复表达更清楚。

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

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