I want to find the optimal way to run this query, here the details, lets say the following are my tables with their data:
-- User Table
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
-- Entries
INSERT INTO `users` VALUES (1,'user_a');
INSERT INTO `users` VALUES (2,'user_b');
INSERT INTO `users` VALUES (3,'user_c');
-- User Log Table
DROP TABLE IF EXISTS `user_log`;
CREATE TABLE `user_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`idrel` int(11) NOT NULL,
`event` varchar(20) NOT NULL,
`log` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `idrel` (`idrel`,`log`)
) ENGINE=MyISAM;
-- Entries
INSERT INTO `user_log` VALUES (1,1,'log1','2014-01-01 13:00:00');
INSERT INTO `user_log` VALUES (2,1,'log2','2014-01-02 13:00:00');
INSERT INTO `user_log` VALUES (3,2,'log3','2014-01-03 13:00:00');
INSERT INTO `user_log` VALUES (4,2,'log4','2014-01-04 13:00:00');
INSERT INTO `user_log` VALUES (5,3,'log5','2014-01-05 13:00:00');
INSERT INTO `user_log` VALUES (6,3,'log6','2014-01-06 13:00:00');
And I want to query the users joining the latest event logged, I have found two ways to do this but I don't know which one is the best (talking about speed when both tables grow) or if there is another way, here are my queries:
-- Query 1
SELECT
u.id,
u.name,
l2.event as last_record
FROM
users AS u
INNER JOIN
(
SELECT
idrel,
MAX(id) as last_id
FROM user_log
GROUP BY
idrel
) AS l1
ON (l1.idrel = u.id)
INNER JOIN
user_log AS l2
ON (l2.id = l1.last_id);
Which gives me this result:
+----+--------+-------------+
| id | name | last_record |
+----+--------+-------------+
| 1 | user_a | log2 |
| 2 | user_b | log4 |
| 3 | user_c | log6 |
+----+--------+-------------+
3 rows in set (0.00 sec)
-- Query 2
SELECT
u.id,
u.name,
(
SELECT event FROM user_log WHERE idrel = u.id ORDER BY log DESC LIMIT 1
) AS last_record
FROM
users AS u;
And the result:
+----+--------+-------------+
| id | name | last_record |
+----+--------+-------------+
| 1 | user_a | log2 |
| 2 | user_b | log4 |
| 3 | user_c | log6 |
+----+--------+-------------+
3 rows in set (0.00 sec)
Which one could be the best way? Is there any other better way?
See Question&Answers more detail:
os