PostgreSQL:内部加入特定值

标签 postgresql select inner-join

  1. 这样做是否更好(主要是性能方面):

    SELECT u.email, s.id
    FROM users s, sessions s
    WHERE u.id = s.user_id
    AND u.id = 1
    

    或:

    SELECT u.email, s.id
    FROM users s, sessions s
    WHERE u.id = 1
    AND s.user_id = 1
    
  2. 关于:

    DELETE FROM users u
    USING sessions s
    WHERE u.id = s.user_id
    AND u.id = 1
    AND s.id = 2
    RETURNING TRUE;
    

    或:

    DELETE FROM users u
    USING sessions s
    WHERE u.id = 1
    AND s.user_id = 1
    AND s.id = 2
    RETURNING TRUE;
    

表架构:

CREATE EXTENSION "uuid-ossp";

CREATE TABLE users (
    id bigserial PRIMARY KEY,
    email varchar(254) NOT NULL,
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX on users (lower(email));

CREATE TABLE sessions (
    user_id bigint PRIMARY KEY REFERENCES users ON DELETE CASCADE,
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);

最佳答案

每当您指定一个特定值而不是一个潜在的值范围时,具有常量值的查询应该更快(尽管使用索引,它可能不会那么快)。

您可以对两者进行EXPLAIN ANALYZE,以查看估算值与实际值。

我相信,由于查询的第一部分是查看两列是否相等,因此需要将它们全部进行比较,然后通过查询的第二部分进一步过滤。

如果您提前知道这两个值,我认为它不仅可能表现得更好,而且在代码中明确指定这两个值也更易读。

编辑: 注意:对于少量数据,查询计划看起来几乎相同:

Nested Loop (cost=0.30..16.34 rows=1 width=532) -> Index Scan using users_pkey on users u (cost=0.14..8.16 rows=1 width=524) Index Cond: (id = 1) -> Index Scan using sessions_pkey on sessions s (cost=0.15..8.17 rows=1 width=24) Index Cond: (user_id = 1)

Nested Loop (cost=0.30..16.34 rows=1 width=532) -> Index Scan using users_pkey on users u (cost=0.14..8.16 rows=1 width=516) Index Cond: (id = 1) -> Index Scan using sessions_pkey on sessions s (cost=0.15..8.17 rows=1 width=16) Index Cond: (user_id = 1)

SQL fiddle :http://sqlfiddle.com/#!15/c9ac7/4

但是,您应该使用您的数据集进行尝试,以确认查询规划器在两种情况下都为您的数据选择了相同的计划。

关于PostgreSQL:内部加入特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23506488/

相关文章:

mysql order by with union 似乎不起作用

mysql - 如何让 MySQL 优化器在加入时首先使用我的索引?

python - 如何根据某些条件(包括日期时间)映射多个 Pandas Dataframe 中的值?

sql - 无法绑定(bind)多部分标识符

postgresql - 数据库连接在Golang中出错了吗?

c++ - 选择 PostgreSQL 的列数

postgresql - 如何从 UNION 查询结果中删除重复项?

MYSQL IF SELECT COUNT() 大于零 select * from table else return nothing found

数据库性能 : filtering on column vs. 分表

SQL JOIN AND OR 条件