We run specs in discourse, and from Database we find a slow query((6480259 nanosecond) compared with similar query) with unnecessary DISTINCT produced by
site_settings_controller.rb#L141as follows:
SELECT
DISTINCT users.id
FROM
"users" CROSS
JOIN tags t
LEFT JOIN tag_users tu ON users.id = tu.user_id
AND t.id = tu.tag_id
WHERE
(
t.id IN (1825)
AND tu.notification_level IS NULL
)
When tags.id and notification_level are specify value, because of UNIQUE (tag_id, user_id, notification_level) in tag_users and PRIMARY KEY(id) in tags, both cross join and left join will not create duplicate
records which means that we can remove DISTINCT to accelerate query.
This opt query take 4538891 nanosecond(improve 30%)