Answer the question
In order to leave comments, you need to log in
How to create the most optimal query with a search for the same field in different PostgreSQL tables and sort by it in the final result?
PostgreSQL 9+
DB
There are several tables of different entities, they have several identical fields (name, price, description,...).
They are combined into one list through a linking table for display.
This table looks like this:
CREATE TABLE section_items(
id serial not null primary key,
section_id int4, -- ссылка на секцию, к которой относится привязка
uni_id int4, -- универсальное ID, которое ссылается на разные таблицы, в зависимости от type_item
type_item int4, -- хранит тип сущности, который необходимо выводить, по ней определяется к какой таблице надо обращаться за данными
sort_num int4
);
select section_items.*, (/* тут предполагаю какая-нибудь функция выборки полей */) as name
from section_items
/*тут длинный запрос объединения и получения name из разных сущностей*/
order by name
limit 12 offset 0;
id | section_id | uni_id | type_item | name
------------------------------------------------
2 | 1 | 24 | 3 | Guitar Learning Webinar
15 | 1 | 117 | 1 | Chess course
25 | 1 | 14 | 1 | Mental Mathematics Course
116 | 1 | 24 | 2 | Programming Learning Test
....
Answer the question
In order to leave comments, you need to log in
I recommend taking a closer look at the materialized view, as already advised earlier.
The peculiarity is that using the name search field in the materialized view, you can build a gist/gin index and use a quick search by %like% (see
https ://postgrespro.ru/docs/postgrespro/9.5/pgtrgm...
note that the materialized view must be updated manually by periodically executing the command
REFRESH MATERIALIZED VIEW mymatview;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question