简体   繁体   中英

Optimize MySQL query for Many-To-Many Join on tags

I need to select all articles that are linked to a particular tag, but I also want all other tags associated with each article. With my limited SQL knowledge, I made the following MySQL query which works, but doesn't seem very efficient.

SELECT a.id, a.name, c.id AS topic_id, c.name AS topic, GROUP_CONCAT(t.id) AS tag_ids, GROUP_CONCAT(t.name) AS tags, a.description
FROM tag t 
LEFT JOIN artifacts_tags j ON t.id = j.tag_id
LEFT JOIN artifact a ON a.id = j.artifact_id
LEFT JOIN topic c ON c.id = a.topic_id

LEFT JOIN artifacts_tags aj ON a.id = aj.artifact_id
LEFT JOIN tag ts ON ts.id = aj.tag_id
WHERE ts.slug = 'summer'
AND a.is_public = 1 
GROUP BY a.id

I would appreciate if anyone could suggest a more efficient query.

Actually, I also need similar tags (all tags belonging to the topic that the tag with slug 'summer' belongs to) but I have another query for that. It would be better if I can get similar tags with the same query but I don't know how. The table tag has Many-to-One relation with topic table.

The SQL retrieves columns that are neither in an aggregate function nor the GROUP BY expression, so these values will be non-deterministic in the result. SQL检索既不在聚合函数中也不在GROUP BY表达式中的列,因此这些值在结果中将是不确定的。

This will force the use of a temporary table and filesort, which can be a huge performance problem and can consume large amounts of memory and temporary space on disk. 这将强制使用临时表和filesort,这可能是一个巨大的性能问题,并且可能会占用磁盘上的大量内存和临时空间。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM