如何根据用户的第一次输入更新字段?

时间:2017-08-10 06:45:36

标签: mysql sql-update

我有一个表名设备。

+---------+---------------+---------------------+
| user_id | device_status | created_at          |
+---------+---------------+---------------------+
|       1 |             0 | 2017-03-10 10:39:41 |
|       1 |             0 | 2017-03-14 10:19:33 |
|       2 |             0 | 2017-03-14 10:57:59 |
|       1 |             0 | 2017-03-15 05:58:51 |
|       3 |             0 | 2017-03-15 06:01:32 |
|       3 |             0 | 2017-03-15 12:10:13 |
+---------+---------------+---------------------+

我想要做的是更新已存储在mysql表中的user_id的device_status

例如,我们有3行user_id 1.with created_at date。我想更新user_id 1的device_status created_at日期2017-03-10 10:39:41。

编辑1:我使用的查询

UPDATE devices 
   SET device_status = 1 
 WHERE created_at = (SELECT created_at 
                       FROM (SELECT MIN(created_at) AS created_at 
                               FROM devices) AS t);

但此查询仅更新了一条记录(2017-03-10 10:39:41)。 我想更新

|       2 |             0 | 2017-03-14 10:57:59 |

|       3 |             0 | 2017-03-15 06:01:32 |

记录。

2 个答案:

答案 0 :(得分:2)

如果所有日期都是互斥的,您可以按user_id分组:

UPDATE devices 
   SET device_status = 1 
 WHERE created_at IN (SELECT created_at 
                        FROM (SELECT MIN(created_at) AS created_at 
                                FROM devices
                               GROUP BY user_id) AS t);

答案 1 :(得分:0)

在子查询中使用min()函数和where子句。

update devices set device_status=1 where user_id = 1 and 
created_at = (select min(created_at)  where user_id = 1);

希望它能解决你的问题。