Answer the question
In order to leave comments, you need to log in
How to properly use View in PostgreSQL?
I know how to create a View and how to get data from there. The question is: are these views -
1. is it something like an SQL command interpreter? When I make a query like `SELECT * FROM mycustomview` is my query just a wrapper for the query I wrote when creating this View? In this case, it's only convenience, not performance.
2. or View is the real tables generated from all data which are received from that request that I used at creation of View? In this case, it greatly affects not only convenience but also performance.
If the View acts as an interpreter (1), are there any generally accepted approaches for doing what I described under number 2?
In recent versions of Postgres, there are more and more chips for working with json. Does it make sense to create triggers or rules so that data from certain tables is added to a new special table to avoid having to make complex queries to get this data?
Example:
CREATE TABLE "public"."user" (
"email" varchar(36) NOT NULL COLLATE "default",
"password" varchar(16) NOT NULL COLLATE "default",
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
CONSTRAINT "User_pkey" PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."user" OWNER TO "postgres";
CREATE UNIQUE INDEX "users_id_key" ON "public"."user" USING btree("id" ASC NULLS LAST);
CREATE TABLE "public"."friend" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" varchar(36) NOT NULL COLLATE "default",
CONSTRAINT "ability_pkey" PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE,
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."friend" OWNER TO "postgres";
CREATE UNIQUE INDEX "ability_id_key" ON "public"."friend" USING btree("id" ASC NULLS LAST);
CREATE TABLE "public"."user_friend" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"owner" uuid NOT NULL,
"friend" uuid NOT NULL,
CONSTRAINT "ability_relation_pkey" PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "owner" FOREIGN KEY ("owner") REFERENCES "public"."user" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "friend" FOREIGN KEY ("friend") REFERENCES "public"."friend" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."user_friend" OWNER TO "postgres";
select row_to_json(t)
from (
select public.user.email, (
select array_to_json(array_agg(row_to_json(ability_relations)))
from (
select *
from public.friend
where public.friend.id in (
select public.user_friend.friend
from public.user_friend
where public.user_friend.owner=public.user.id
)
) ability_relations
) as abilities
from public.user
) t
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question