使用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