PostgreSQL-使用多个子查询优化查询

时间:2019-01-06 22:31:49

标签: postgresql performance optimization subquery

我有2个表,userssessions。表格如下:

用户-id(int),name(varchar)

会话-id(int),user_id(int),ip(inet),cookie_identifier(varchar)

所有列都有索引。

现在,我正在尝试查询与特定用户具有相同的ipcookie_identifier会话的所有用户。

这是我的查询:

SELECT *
FROM "users"
WHERE "id" IN
    (SELECT "user_id"
     FROM "sessions"
     WHERE "user_id" <> 1234
       AND ("ip" IN
              (SELECT "ip"
               FROM "sessions"
               WHERE "user_id" = 1234
               GROUP BY "ip")
            OR "cookie_identifier" IN
              (SELECT "cookie_identifier"
               FROM "sessions"
               WHERE "user_id" = 1234
               GROUP BY "cookie_identifier"))
     GROUP BY "user_id")

users表具有约200,000行,sessions表具有约150万行。查询大约需要3-5秒。

是否有可能优化这些结果?

1 个答案:

答案 0 :(得分:0)

作为建议,我建议删除所有分组:

{
    "Scores": [
        {
            "Name": "Bart",
            "Points": 100
        },
        {
            "Name": "Maggie",
            "Points": 75
        },
        {
            "Name": "Lisa",
            "Points": 50
        },
        {
            "Name": "Marge",
            "Points": 25
        },
        {
            "Name": "Homer",
            "Points": 0
        }
    ]
}

如果这没有帮助,请尝试更改以上内容以使用SELECT * FROM users WHERE id IN ( SELECT user_id FROM sessions WHERE user_id <> 1234 AND (ip IN ( SELECT ip FROM sessions WHERE user_id = 1234 ) OR cookie_identifier IN ( SELECT cookie_identifier FROM sessions WHERE user_id = 1234 ) ) ) ; 代替EXISTS

IN