[英]How to use MySQL if statement for column name?
I have table: 我有桌子:
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 | |
+-------------+----------+------+-----+---------+----------------+
where user1_id and user2_id represents users that are swapping and swapped1/swapped2 represent time when they affirm swap. 其中user1_id和user2_id表示正在交换的用户,swapped1 / swapped2表示确认交换的时间。 I need to create mechanism to close swap when both have confirmed swap.
我们需要创建机制来在两者都确认交换时关闭交换。
I need something like this: 我需要这样的东西:
UPDATE swaps SET if(user1_id = ?, swapped1, swapped2) = ? WHERE id=?
where ? 哪里? marks represent current user, current time, swap_id.
标记表示当前用户,当前时间,swap_id。 What I want is to insert time into swapped1 if current user is user1 and into swapped2 if current user is user2.
我想要的是在当前用户是user1时将时间插入swapped1,如果当前用户是user2,则插入swapped2。
Running this query I get error: 运行此查询我收到错误:
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
what means that I am not using if statement correctly. 这意味着我没有正确使用if语句。 Is there a way to perform if statement on column name?
有没有办法在列名上执行if语句?
You can't use IF
on the left side of an assignment, but you can update both columns conditionally: 您不能在作业的左侧使用
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];
You must test always user1_id like this: 你必须像这样测试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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.