There seem to be already a lot of questions/answers to what I'm experiencing, but I couldn't adapt anything I discovered in order to fix my problem.
A have a courses
table, and another views
table.
The views
table is meant to track page views of all the site's modules, for example:
id | table | id_row | ip | created_at |
---|---|---|---|---|
1 | courses | 57 | xx | timestamp |
2 | blog | 12 | xx | timestamp |
In our CMS, we are trying to get all the courses to a table, while getting their viewcount, but that viewcount is taking too long to render, as there are hundreds of courses and thousands of views.
Here's a simplified version of my query:
SELECT c.*,
(
SELECT COUNT(*) FROM t_applications AS a
WHERE a.id_course = c.id
GROUP BY a.id_course
) AS applications,
(
SELECT COUNT(*)
FROM t_views AS v
WHERE v.table = 'courses'
AND v.id_row = c.id
GROUP BY v.id_row
) as views
FROM t_courses AS c;
I've tried switching it up with JOIN
and other techniques, but nothing seems to work.
Would appreciate some insight on how to improve this query's performance, as it's taking over a minute to render.
EDIT:
As per requested by some people, here are my SHOW CREATE TABLE
of all 3 tables, again, simplified.
CREATE TABLE `t_courses`
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL,
-- other data
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=516 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci
CREATE TABLE `t_views` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`table` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL,
`id_row` bigint(20) unsigned NOT NULL,
`ip` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=47032 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci
CREATE TABLE `t_applications` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`id_course` bigint(20) unsigned NOT NULL,
-- other data
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4177 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci