我有桌子:
mysql> DESCRIBE swaps;
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user1_id | int(11) | NO | | NULL | |
| user2_id | int(11) | NO | | NULL | |
| hasto | int(11) | NO | | NULL | |
| requested | datetime | NO | | NULL | |
| accepted | datetime | YES | | NULL | |
| swapped1 | datetime | YES | | NULL | |
| swapped2 | datetime | YES | | NULL | |
| rejected | datetime | YES | | NULL | |
| rejected_by | int(11) | YES | | NULL | |
+-------------+----------+------+-----+---------+----------------+
其中user1_id和user2_id表示正在交换的用户,swapped1 / swapped2表示确认交换的时间。当两者都确认交换时,我需要创建关闭交换的机制。
我需要这样的东西:
UPDATE swaps SET if(user1_id = ?, swapped1, swapped2) = ? WHERE id=?
在哪里?标记表示当前用户,当前时间,swap_id。我想要的是在当前用户是user1时将时间插入swapped1,如果当前用户是user2,则插入swapped2。
运行此查询我收到错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if(user1_id = '3', swapped1, swapped2) = '2017-01-13 07:34:08' WHERE id='3'' at line 1
这意味着我没有正确使用if语句。有没有办法在列名上执行if语句?
答案 0 :(得分:0)
您无法在作业的左侧使用IF
,但您可以有条件地更新这两列:
UPDATE swaps
SET swapped1 = IF(user1_id = [current_user], [current_time], swapped1)
, swapped2 = IF(user2_id = [current_user], [current_time], swapped2)
WHERE id = [swap_id];
答案 1 :(得分:0)
你必须像这样测试user1_id:
UPDATE swaps
SET
swapped1 if(user1_id = 3, '2017-01-13 07:34:08' , swapped1),
swapped2 if(user1_id = 3, swapped2, '2017-01-13 07:34:08' )
WHERE id=3;