简体   繁体   English

插入行或更新(如果存在)(如果存在多个条件)

[英]Insert row or update if exists (multiple conditions if exists)

I have a row that contains 3 fields: 我一行包含3个字段:
day earnings person 日薪人
1 3 1 1 3 1
1 7 2 1 7 2
1 4 3 1 4 3
2 6 1 2 6 1
2 9 2 2 9 2

The idea is that every person earns money/day, now what I want is to update the earnings for a day for a person, but if that person didn't have any earnings (the row for that person/day is not there) than insert the row 这个想法是每个人每天都赚钱,现在我想要的是更新一个人一天的收入,但是如果那个人没有任何收入(那个人/天的行不存在),那么插入行

Example
day earnings person 日薪人
1 3 1 1 3 1

In this case, it would update the row and add 1 earning: 在这种情况下,它将更新该行并增加1收入:
day earnings person 日薪人
1 4 1 1 4 1

If the original row was not preasent (so person and date did not exist) than insert a new row like: 如果原始行不存在(因此人员和日期不存在),则插入新行,例如:
day earnings person 日薪人
1 1 1 1 1 1

I know that there exists the command INSERT ON DUPLICATE KEY UPDATE 我知道存在命令INSERT ON DUPLICATE KEY UPDATE

But this works only for 1 unique index column (from what I read), I need it to work with day and person (2 columns). 但这仅适用于1个唯一索引列(根据我的阅读),我需要它与day和person一起使用(2列)。

I hope I explained correctly and someone can help. 我希望我能正确解释,有人可以提供帮助。 I know it's possible to do this from PHP but to avoid multiple queries (it's important) I would like to know if it's possible to make it in 1 query. 我知道可以从PHP进行此操作,但要避免多次查询(这很重要),我想知道是否有可能在1个查询中进行查询。

Here is what works if I only consider the date column (that is unique) any chance I can change it to work in my case? 如果我仅考虑日期列(唯一),可以在我的情况下对其进行更改,那么这是可行的?

INSERT INTO table (day, earnings, person)
VALUES ('1',earnings,1)
ON DUPLICATE KEY UPDATE
earnings = VALUES(earnings+1)

You can make it work by adding a composite unique key on both day and person. 您可以通过在日期和人员上添加复合唯一键来使其工作。

ALTER TABLE `myTable` ADD UNIQUE (`day`,`person`);

And then 接着

INSERT INTO `myTable` (day, earnings, person)
VALUES ('1',$earnings,1)
ON DUPLICATE KEY UPDATE
earnings = earnings + $earnings

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

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