I have tried googling and checking questions on this site, but I think the terms "users" and "logged in" is throwing the answers.
I have an application that uses a MySQL database where User details are stored on the Users table. The MySQL server version is: 5.7.42-cll-lve – MySQL Community Server – (GPL).
I am trying to find the maximum concurrent users the application ever had, and when that was. Note that by users I mean users of my application, not database users. As a bonus, knowing the actual usernames (not just the number of users) would be helpful as well.
The table structure is as follows:
CREATE TABLE `Users` (
`user_ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(25) NOT NULL,
`last_login` datetime NOT NULL,
`last_logout` datetime NOT NULL,
PRIMARY KEY (`user_ID`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=1813 DEFAULT CHARSET=utf8
The query I have written based on help from this site is as follows:
SELECT user_ID, username, last_login, last_logout, last_logout - last_login AS seconds
FROM Users
WHERE last_login < last_logout
AND last_logout > last_login
ORDER BY last_login;
But that is not giving me the results I want. Note that the last_login and last_logout columns are stored as datetime.
I’ve also tried to use a JOIN similar to the below, but that’s also not working:
SELECT user_ID, username, last_login, last_logout, last_logout -last_login AS seconds
FROM Users A
INNER JOIN Users B ON (B.last_login <= last_logout)
AND (B.last_logout >= A.last_login_datetime)
AND A.user_ID <> B.user_ID;
What am I doing wrong?
2
Answers
tried this one
Maybe like this:
It’s a
UNION ALL
query build fromThe only difference is the switch between
u1
andu2
. In the outer query, we group by login date,group_concat
the username and count how many there is.Fiddle: https://dbfiddle.uk/Nl4Qp5OX