我有一个包含数千条车辆数据记录的表,该表被该表引用,其中存储了这些车辆的图像。
第二张表大约有数百万条记录,因为每辆车都有大约 15 张图像。
现在我面临一个问题 - 当我想删除车辆时,大约需要 5 分钟。车辆设置为 ON DELETE CASCADE。
你能帮我吗,要创建哪个索引以及在哪里创建,以便快速删除?
\d catalog_vehicle
Table "public.catalog_vehicle"
Column | Type | Collation | Nullable | Default
---------------------+--------------------------+-----------+----------+---------------------------------------------
id | bigint | | not null | nextval('catalog_vehicle_id_seq'::regclass)
type | smallint | | not null |
trim | character varying(64) | | not null |
slug | character varying(32) | | not null |
year | smallint | | not null |
...
...
...
Indexes:
"catalog_vehicle_pkey" PRIMARY KEY, btree (id)
"catalog_vehicle_slug_key" UNIQUE CONSTRAINT, btree (slug)
"catalog_vehicle_color_id_5691a4b9" btree (color_id)
...
...
...
"catalog_vehicle_slug_508ef2db_like" btree (slug varchar_pattern_ops)
Check constraints:
...
...
...
Foreign-key constraints:
...
...
...
Referenced by:
TABLE "catalog_image" CONSTRAINT "catalog_image_vehicle_id_16ba1633_fk_catalog_vehicle_id" FOREIGN KEY (vehicle_id) REFERENCES catalog_vehicle(id) DEFERRABLE INITIALLY DEFERRED
soldvehicle=# \d catalog_image
Table "public.catalog_image"
Column | Type | Collation | Nullable | Default
------------+------------------------+-----------+----------+-------------------------------------------
id | bigint | | not null | nextval('catalog_image_id_seq'::regclass)
image | character varying(100) | | not null |
width | integer | | not null |
height | integer | | not null |
vehicle_id | bigint | | not null |
Indexes:
"catalog_image_pkey" PRIMARY KEY, btree (id)
"catalog_image_vehicle_id_16ba1633" btree (vehicle_id)
Check constraints:
"catalog_image_height_check" CHECK (height >= 0)
"catalog_image_width_check" CHECK (width >= 0)
Foreign-key constraints:
"catalog_image_vehicle_id_16ba1633_fk_catalog_vehicle_id" FOREIGN KEY (vehicle_id) REFERENCES catalog_vehicle(id) DEFERRABLE INITIALLY DEFERRED
您需要一个表上的索引,该索引引用您要从中删除的表:
这是因为每个
DELETE
oncatalog_vehicle
都必须确保不引用即将删除的行。它通过运行相当于catalog_image
如果包含许多行,则该语句必须执行慢速顺序扫描。