我有一个表,其中有很多外键,我需要将它们进行内连接以便进行搜索。可能有 10 个以上,这意味着我必须执行 10 次内部联接。与我要连接的庞大(数百万行)表相比,要连接的每个表可能只有几行。
我只需要知道连接是否是执行此操作的快速方法(仅使用 Postgres),或者是否有更聪明的方法可以使用子查询或其他方式来执行此操作。
以下是一些虚构的数据作为示例:
create table a (
a_id serial primary key,
name character varying(32)
);
create table b (
b_id serial primary key,
name character varying(32)
);
--just 2 tables for simplicity, but i really need like 10 or more
create table big_table (
big_id serial primary key,
a_id int references a(a_id),
b_id int references b(b_id)
);
--filter big_table based on the name column of a and b
--big_table only contains fks to a and b, so in this example im using
--left joins so i can compare by the name column
select big_id,a.name,b.name from big_table
left join a using (a_id)
left join b using (b_id)
where (? is null or a.name=?) and (? is null or b.name=?);
最佳答案
基本上,联接是一种快速的方法。哪种方式最快取决于具体要求。一些提示:
WHERE
子句的目的不清楚。看来您打算加入所有查找表并为每个查找表添加一个条件,而实际上您只需要其中的一些。那是低效的。而是使用dynamic-sql并且仅在查询中包含您实际需要的内容。对于当前查询,由于主表中的所有 fk 列都可以为
NULL
,因此您必须使用LEFT JOIN
而不是JOIN
,否则您将排除 fk 列中具有NULL
值的行。查找表中的
name
列当然应该定义为NOT NULL
。我不会使用非描述性的列名称"name"
,这是一个无用的命名约定。 I also would usetext
instead ofvarchar(32)
.
关于sql - 内连接性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23175010/