I'm trying to find any ways to optimize this statement:
INSERT INTO achievements
(
nick, cost, achievement_type, announced_in_chat, shown_on_stream, dt
)
SELECT nick, 2000, 0, TRUE, FALSE, NOW()
FROM points_log
WHERE nick NOT IN
(
SELECT nick from achievements
WHERE achievement_type = 0 AND stream_online = TRUE
)
GROUP BY nick HAVING SUM(amount) >= 2000;
The goal is to find people who have scored 2000 points (SUM(amount)) from the points_log and are also not in achievements (nick NOT IN). Any help would be greatly appreciated.
Here are the achievements and points_log tables:
mysql> describe achievements;
+-------------------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+-----------------------+------+-----+---------+----------------+
| id | mediumint(8) unsigned | NO | PRI | NULL | auto_increment |
| nick | char(25) | NO | PRI | NULL | |
| cost | decimal(8,4) | NO | MUL | NULL | |
| achievement_type | tinyint(3) unsigned | NO | MUL | NULL | |
| announced_in_chat | tinyint(1) | NO | | NULL | |
| shown_on_stream | tinyint(1) | NO | | NULL | |
| dt | datetime | NO | PRI | NULL | |
+-------------------+-----------------------+------+-----+---------+----------------+
7 rows in set (0.01 sec)
mysql> describe points_log;
+-------------------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+-----------------------+------+-----+---------+----------------+
| id | mediumint(8) unsigned | NO | PRI | NULL | auto_increment |
| nick | char(25) | NO | PRI | NULL | |
| amount | decimal(10,4) | YES | MUL | NULL | |
| stream_online | tinyint(1) | NO | MUL | NULL | |
| modification_type | tinyint(3) unsigned | NO | MUL | NULL | |
| dt | datetime | NO | PRI | NULL | |
+-------------------+-----------------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)