假设我有一个表来存储每个用户的博客(表名是 blogs)。 而且还要有一个表来存储用户喜欢的其他用户的博客(表名是 likmedBlogs),是吗?
所以为了检索它们,我只是这样做: -选择用户的博客。 -添加他喜欢的博客。
$q = mysql_query("
SELECT id
FROM blogs
WHERE (iduser = $id)
OR id IN
(SELECT idblog
FROM likedBlogs
WHERE iduser='$id')
AND (id > 0)
ORDER BY id DESC
LIMIT 20
") or die(mysql_error());
我可以做得更好吗? (您如何评价这个查询的性能?)
谢谢
最佳答案
我相信您可以使用 EXISTS 而不是 IN 更好地重构它。
IN
要求返回整个结果集,然后开始搜索一个值,但是 EXISTS
逐行检查并在找到第一次出现时中断内部查询。
SELECT id
FROM blogs
WHERE (iduser = $id)
OR EXISTS
(SELECT idblog
FROM likedBlogs
WHERE iduser='$id' AND idblog = id)
AND (id > 0)
ORDER BY id
DESC LIMIT 20
参见 Optimizing IN/=ANY Subqueries
very useful optimization is to “inform” the subquery that the only rows of interest are those where the inner expression inner_expr is equal to outer_expr. This is done by pushing down an appropriate equality into the subquery's WHERE clause. That is, the comparison is converted to this: EXISTS (SELECT 1 FROM ... WHERE subquery_where AND outer_expr=inner_expr)
关于mysql - 优化查询 : Select in Select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7902611/