所以我有这个超级查询,它根据它们与原始文章共有的标签数量(在 $id 变量中提供)来查找“相关文章”。我不知道实际查询是否重要,但这里是 Justin Case。
现在,我从未在实际项目中实际使用过过程,但我读过它们应该更快,部分原因是 MySQL 引擎不需要每次都解释代码。但是,当我将相同的代码放入一个过程并调用该过程时,执行时间平均要长约 450 倍。
为什么?是因为它返回多行吗?程序臭吗?是因为我必须在我的程序中使用输入变量吗?450是一堆!
SELECT a.id, a.image, a.title, a.excerpt, a.permalink, COUNT(rel.category_id) AS n
FROM articles AS a
JOIN category_relations AS rel ON rel.article_id = a.id
JOIN categories AS c ON rel.category_id = c.id
WHERE rel.category_id IN (SELECT category_id
FROM category_relations
WHERE article_id = {$id})
AND a.id != {$id}
AND c.type = 1
GROUP BY rel.article_id
ORDER BY n DESC, publish_date DESC
LIMIT 10
用于创建过程的代码:
DROP PROCEDURE IF EXISTS get_related_articles;
DELIMITER //
CREATE PROCEDURE get_related_articles(IN id INT)
BEGIN
SELECT a.id, a.image, a.title, a.excerpt, a.permalink, COUNT(rel.category_id) AS n
FROM articles AS a
JOIN category_relations AS rel ON rel.article_id = a.id
JOIN categories AS c ON rel.category_id = c.id
WHERE rel.category_id IN ( SELECT category_id FROM category_relations WHERE article_id = id)
AND a.id != id
AND c.type = 1
GROUP BY rel.article_id
ORDER BY n DESC, publish_date DESC
LIMIT 10;
END //
DELIMITER ;