【问题标题】:conditional update mySQL entrys using multiple rows使用多行条件更新 mySQL 条目
【发布时间】:2018-07-09 20:37:32
【问题描述】:

所以我有一个数据库,其中包含以下列:nameuidpoints。 基本上我想将一个条目的分数减少100,但前提是points > 100。但同时我想将另一个条目上的积分增加100,但前提是第一个条目上的points > 100

IF <user1_points > 100> : Increase user2_points by 100, decrease user1_points by 100
ELSE: do nothing

我试着环顾四周,但我找不到一个好的解决方案(只有一些带有EXISTS,或者不是mySQL/InnoDB,但我需要一个特定的条件)

我的数据库如下所示:

| name | uid | points |
|------+-----+--------|
| Foo  |  1  |  100   |
|------+-----+--------|
| Bar  |  2  |  200   |
|------+-----+--------|

我的预期结果是:

| name | uid | points |
|------+-----+--------|
| Foo  |  1  |  200   |
|------+-----+--------|
| Bar  |  2  |  100   |
|------+-----+--------|

但前提是points(uid=1) &gt; 100。否则什么都不做。

我基本上是在寻找表达短语的正确方式(伪代码):

IF uid=2.points &gt;= 100 THEN SET uid=1.points += 100 AND uid=1.points -= 100

【问题讨论】:

  • 更新您的问题添加适当的数据样本和预期的结果..

标签: mysql database conditional


【解决方案1】:

我认为您只是在寻找UPDATE 某些字段。

试试这个语法:

UPDATE table_name
SET points = points + 100
WHERE points > 100
AND some_condition;

同样,当满足你的其他条件时,你可以减去分数

UPDATE table_name
SET points = points - 100
WHERE points > 100
AND some_other_condition;

更多: https://www.w3schools.com/sql/sql_update.asp

【讨论】:

  • WHERE 有点问题。如何从 WHERE 子句中的另一行中进行选择?因为我基本上需要说points(uid=1) = points(uid=1) + 100points(uid=2) = points(uid=2) - 100
  • 你的情况如何?
  • AND name = 'Foo'
  • 所以基本上最好的方法就是调用 2 个查询?但是,我仍然必须按列 UID 调用行。那我怎么说update ... set points = points + 100 if points &gt; 100 where uid=2?我真的想不出一种表达方式
猜你喜欢
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多