The pg database is a super simple way to find out all tables without primary keys, only need to use a system table

Chapter 1 Problem Solving

step1 Find out the English names of all the tables in the database

Find out the English names of all the tables in the database and name them Table A

SELECT * from pg_class where pg_class.reltoastrelid!=0 and pg_class.relname not like 'pg_%' and pg_class.relname not like 'sql_%'

step2 Find out all tables with primary keys

Find all tables with primary keys, named table B

SELECT pg_class.relname from pg_class where pg_class.relname like '%_pkey'

step3 Find out the table without primary key

The method is: take out the elements that are not in the B table and remove the suffix '_pkey' from the A table to complete

SELECT A.a1 from (SELECT pg_class.relname a1 from pg_class where pg_class.reltoastrelid!=0 and pg_class.relname not like 'pg_%' and pg_class.relname not like 'sql_%' ) as A
where A.a1 not in  
(SELECT split_part(pg_class.relname,'_pkey',1) as aa from pg_class where pg_class.relname like '%_pkey')

Chapter 2 Knowledge Supplement

pg_constraint This system table stores check constraints, primary keys, unique constraints, and foreign key constraints for table objects in PostgreSQL.
The pg_attribute system table stores field information of all tables (including system tables such as pg_class). Each field in each table in the database has a row in the pg_attribute table.
pg_type This system table stores information about data types.
pg_class This system table records the metadata of data tables, indexes (still need to refer to pg_index), sequences, views, composite types and some special relation types

pg_constraint.conname (constraint name)
pg_constraint.conrelid (the table where the constraint is located, 0 if it is not a
table constraint) pg_constraint.conkey (if it is a table constraint, the list of fields controlled by the constraint)
pg_constraint.contypec (check constraint, f = foreign key constraint, p = primary key constraint, u = unique constraint)
pg_constraint.conkey (if it is a table constraint (including foreign keys, but not constraint triggers), list of constraint fields)
pg_attribute.attname (field name)
pg_attribute.attrelid (the table this field belongs to)
pg_attribute.atttypid (the data type of the field)
pg_attribute.attnum (the number of fields. Common fields are counted from 1. System fields (such as oid) have (arbitrary) negative numbers)
pg_type.typname (data type name)
pg_type.oid (row identifier (hidden attribute; must be explicitly selected))
pg_class.relname (data type name)
pg_class.oid (row identifier (hidden attribute; must be explicitly selected))

Guess you like

Origin blog.csdn.net/quantam/article/details/109308283