How to update User Logged in Time for a specific user in MySQL?

MySQLMySQLi Database

For this, use ORDER BY along with LIMIT. Let us first create a table wherein we have a column with User id, logged in time, and name −

mysql> create table DemoTable1911
   (
   UserId int,
   UserLoggedInTime time,
   UserName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1911 values(100,'7:32:00','Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1911 values(101,'5:00:00','David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1911 values(102,'6:10:20','Mike');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1911 values(103,'3:55:00','Carol');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1911;

This will produce the following output −

+--------+------------------+----------+
| UserId | UserLoggedInTime | UserName |
+--------+------------------+----------+
|    100 | 07:32:00         |    Chris |
|    101 | 05:00:00         |    David |
|    102 | 06:10:20         |     Mike |
|    103 | 03:55:00         |    Carol |
+--------+------------------+----------+
4 rows in set (0.00 sec)

Here is the query to update logged in time for a specific user “Carol” −

mysql> update DemoTable1911
     set UserLoggedInTime='12:30:45'
     where UserName='Carol'
     order by UserId DESC
     Limit 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1911;

This will produce the following output −

+--------+------------------+----------+
| UserId | UserLoggedInTime | UserName |
+--------+------------------+----------+
|    100 | 07:32:00         |    Chris |
|    101 | 05:00:00         |    David |
|    102 | 06:10:20         |     Mike |
|    103 | 12:30:45         |    Carol |
+--------+------------------+----------+
4 rows in set (0.00 sec)
raja
Published on 30-Dec-2019 11:06:22
Advertisements