我有一个表,其中包含一个表中 C 源文件的名称和文件系统位置,一个由第二个表中的源文件演示的编程原则的相关类别列表,然后是一个一对多的联结表对于与每个源文件关联的类别。(下面的表定义问题)
我需要做的是从源文件表中获取在联结表中file_id
没有关联条目的 s 列表。file_id
我已经使用一个子句完成了这项工作,except
该子句依赖于inner join
从联结表中选择记录,其中file_id
s 出现在联结表中,例如
select distinct file_id from c_file
except (
select distinct c_file.file_id from c_file
inner join c_file_topic_rel
on c_file_topic_rel.file_id = c_file.file_id
where exists (
select distinct file_id from c_file_topic_rel
)
)
order by file_id;
c_file
这工作正常,但我不是 SQL 大师,我怀疑我花了很长时间才从不在联结表中的表中获取记录c_file_topic_rel
。有没有更好的方法来隔离连接表中没有条目的记录?(表中大约有 15,000 个条目c_file
,如果大小很重要的话——它相对较小)
表定义
Default
删除该列以防止过度滚动。如果相关,我很乐意添加完整的定义。
c_file 表
Table "public.c_file"
Column | Type | Collation | Nullable |
---------+-----------------------------+-----------+----------+
file_id | integer | | not null | ...
fname | character varying(64) | | not null |
dirname | character varying(128) | | not null |
mtime | timestamp without time zone | | not null | ...
created | timestamp without time zone | | not null | ...
Indexes:
"cfile_pkey" PRIMARY KEY, btree (file_id)
"cfile_fname_key" UNIQUE CONSTRAINT, btree (fname)
c_topics 表
Table "public.c_topics"
Column | Type | Collation | Nullable |
-------------------+-----------------------------+-----------+----------+
topic_id | integer | | not null | ...
topic | character varying(32) | | not null |
topic_description | character varying(96) | | not null |
created | timestamp without time zone | | | ...
modified | timestamp without time zone | | | ...
seq | smallint | | |
Indexes:
"c_topics_pkey" PRIMARY KEY, btree (topic_id)
"c_topics_topic_key" UNIQUE CONSTRAINT, btree (topic)
Referenced by:
TABLE "c_file_topic_rel" CONSTRAINT "c_file_topic_rel_topic_id_fkey" FOREIGN KEY (topic_id) REFERENCES c_topics(topic_id)
c_file_topic_rel 联结表
Table "public.c_file_topic_rel"
Column | Type | Collation | Nullable | Default
----------+---------+-----------+----------+---------
file_id | integer | | not null |
topic_id | integer | | not null |
Indexes:
"c_file_topic_rel_file_id_topic_id_key" UNIQUE CONSTRAINT, btree (file_id, topic_id)
Foreign-key constraints:
"c_file_topic_rel_file_id_fkey" FOREIGN KEY (file_id) REFERENCES c_file_bf(file_id)
"c_file_topic_rel_topic_id_fkey" FOREIGN KEY (topic_id) REFERENCES c_topics(topic_id)