使用PostgreSQL,我在查询中加入约10桌,它们都是许多一对多的关系。数据库目前仍然非常小(总共数百行,所有表格组合在一起),但查询速度非常慢(1分钟以上的处理时间)。SQL表连接许多一对多很慢
由于每一个加入相乘的行数(接合具有5个记录2代表的每个将产生25行),其结果很快变得庞大与超过30万行。查询的格式如下:
select * from student_profile sp
join student_profile_skills sps on sp.id = sps.student_profile_id
join student_profile_hobby sph on sp.id = sph.student_profile_id
--and other 8 similar joins
where sp.id = 1;
表格很简单(有2个FKs的联结表)。这里推荐的做法是什么?是查询必须以更优化的方式编写还是使用单独的查询? Thx提前!
附加信息:
CREATE TABLE student_profile
(
id serial NOT NULL,
first_name text NOT NULL,
last_name text NOT NULL,
country_id integer,
city_id integer,
faculty_id integer,
university_id integer,
degree_id integer,
degree_year integer,
created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT student_profile_pkey PRIMARY KEY (id),
CONSTRAINT student_profile_country_id_fkey FOREIGN KEY (country_id) REFERENCES country (id),
CONSTRAINT student_profile_city_id_fkey FOREIGN KEY (city_id) REFERENCES city (id),
CONSTRAINT student_profile_faculty_id_fkey FOREIGN KEY (faculty_id) REFERENCES faculty (id),
CONSTRAINT student_profile_university_id_fkey FOREIGN KEY (university_id) REFERENCES university (id),
CONSTRAINT student_profile_degree_id_fkey FOREIGN KEY (degree_id) REFERENCES degree (id)
);
CREATE TABLE student_profile_skill
(
id serial NOT NULL,
student_profile_id integer NOT NULL,
skill_id integer NOT NULL,
position integer NOT NULL,
created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT student_profile_skill_pkey PRIMARY KEY (id),
CONSTRAINT student_profile_skill_student_profile_id_fkey FOREIGN KEY (student_profile_id) REFERENCES student_profile (id),
CONSTRAINT student_profile_skill_skill_id_fkey FOREIGN KEY (skill_id) REFERENCES skill (id),
CONSTRAINT student_profile_skill_unique UNIQUE (student_profile_id, skill_id),
CONSTRAINT student_profile_skill_position_unique UNIQUE (student_profile_id, position)
);
你能表现出一定的查询和/或表的详细信息? –
你需要给我们的表的DDL – sagi
查询是形式:SELECT * FROM student_profile SP加入student_profile_skills SPS上sp.id = sps.student_profile_id上sp.id = sph.student_profile_id(和其他8种相似的加入student_profile_hobby SPH加入)其中sp.id = 1; – Thibaut