哪种方法会更快?

时间:2014-08-21 16:34:20

标签: sql postgresql left-join database-performance exists

我必须选择用户列表,对于每个用户,我必须返回他是否遵循的信息(由当前/请求用户)。现在我这样查询:

SELECT 
   "User"."name", 
   EXISTS(
      SELECT * FROM "Followings" f WHERE f."FollowedId" = "User"."id" AND f."FollowerId" = 123
   )::boolean AS "isFollowed"
FROM "Users" AS "User" 
ORDER BY "User"."createdAt" 
LIMIT 15

注意:123是检索用户列表的用户的id。

做出这样嵌套的SELECT是个好主意吗?这种查询的表现是什么?

我的第二个想法就是制作"Users" LEFT JOIN "Followings" - 如果跟随加入,则跟随用户。哪种方法会更好?

1 个答案:

答案 0 :(得分:2)

,您的查询是最佳的。我只是简化并删除了多余的演员:

SELECT name
     , EXISTS (
          SELECT 1 FROM "Followings" f
          WHERE  f."FollowedId" = u."id"
          AND    f."FollowerId" = 123
          ) AS "isFollowed"
FROM  "Users" u
ORDER  BY "createdAt" 
LIMIT  15;
  • ::boolean的演员阵容是多余的,因为EXISTS已经返回boolean

使用LEFT JOIN的替代表单执行大致相同或更慢,但更复杂并且依赖于("FollowedId", "FollowerId")是唯一的,或者您可以获得多行,这可能会导致您的{ {1}},因此您需要添加LIMIT。假设唯一对:

GROUP BY