Rechercher et corriger les violations de clés étrangères
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Pour rechercher une clé étrangère dans laquelle la clé primaire correspondante est manquante, exécutez la commande suivante:
Exemple de code
WITHqAS(SELECTconrelid::regclassASfk_table,confrelid::regclassASpk_table,format('(%s)',(selectstring_agg(format('fk.%I',attname),', ')FROMpg_attributeaJOINunnest(conkey)ia(nr)ONia.nr=a.attnumWHEREattrelid=conrelid))ASfk_fields,format('(%s)',(selectstring_agg(format('pk.%I',attname),', ')FROMpg_attributeaJOINunnest(confkey)ia(nr)ONia.nr=a.attnumWHEREattrelid=confrelid))ASpk_fields,pg_get_constraintdef(oid)FROMpg_constraintWHEREcontype='f')SELECTformat($sql$DO$$BEGINRAISENOTICE'checking Foreign Key %3$s%1$s ==> %4$s%2$s';END;$$;SELECT%1$s,%2$sFROM%3$sASfkLEFTJOIN%4$sASpkON%1$s=%2$sWHERE%2$sISNULLAND%1$sISNOTNULL/* any NULL on FK side bypasses FK constraint by design *//* use limit for testing, or detecting that "there is a problem in this table */-- LIMIT 10$sql$,fk_fields,pk_fields,fk_table,pk_table)FROMq\gexec
Le résultat du script doit ressembler à ce qui suit : S'il n'y a pas de résultat, il n'y a pas de violation et vous avez réussi à recompiler votre index.
Sortie
id|pk_id----+-------
|4(1row)
Dans la sortie ci-dessus, la première colonne affiche les colonnes de clé primaire. Dans cet exemple, il s'agit d'une colonne nommée id. La deuxième colonne est la colonne de référence de la clé étrangère. Cela signifie qu'une ligne, pk_id=4, n'a pas de clé primaire parente. Vous pouvez décider si ces clés sont valides et, si ce n'est pas le cas, les supprimer.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eThis code checks for foreign key violations where a foreign key references a non-existent primary key.\u003c/p\u003e\n"],["\u003cp\u003eThe provided SQL script identifies and lists rows in foreign key tables that do not have a corresponding entry in the primary key table.\u003c/p\u003e\n"],["\u003cp\u003eThe script's output displays the foreign key column(s) and the corresponding non-existent primary key column(s).\u003c/p\u003e\n"],["\u003cp\u003eA null value on the foreign key side is by design and bypasses the foreign key constraint, so it will not be identified in the output.\u003c/p\u003e\n"]]],[],null,["# Find and fix foreign key violations\n\nTo check for a foreign key where the\ncorresponding primary key is missing, run the following command: \n\n### Code Sample\n\n```sql\n WITH q AS (\n SELECT conrelid::regclass AS fk_table, \n confrelid::regclass AS pk_table, \n format('(%s)',(select string_agg(format('fk.%I', attname), ', ') \n FROM pg_attribute a \n JOIN unnest(conkey) ia(nr) ON ia.nr = a.attnum\n WHERE attrelid = conrelid)) AS fk_fields, \n format('(%s)',(select string_agg(format('pk.%I', attname), ', ') \n FROM pg_attribute a \n JOIN unnest(confkey) ia(nr) ON ia.nr = a.attnum\n WHERE attrelid = confrelid)) AS pk_fields, \n pg_get_constraintdef(oid)\n FROM pg_constraint\n WHERE contype='f'\n )\n SELECT format(\n $sql$\n DO $$ BEGIN RAISE NOTICE 'checking Foreign Key %3$s%1$s ==\u003e %4$s%2$s'; END;$$;\n SELECT %1$s, %2$s \n FROM %3$s AS fk\n LEFT JOIN %4$s AS pk ON %1$s = %2$s \n WHERE %2$s IS NULL\n AND %1$s IS NOT NULL /* any NULL on FK side bypasses FK constraint by design */\n /* use limit for testing, or detecting that \"there is a problem in this table */\n -- LIMIT 10\n $sql$, fk_fields, pk_fields, fk_table, pk_table\n )\n FROM q\n \\gexec\n \n```\n\nThe output of the script will be similar to the following. If there is no\noutput, there are no violations and you have successfully rebuilt your index. \n\n### Output\n\n```bash\n id | pk_id \n ----+-------\n | 4\n (1 row)\n \n```\n\nIn the above output, the first column shows the primary key columns, in this\nexample, a column named `id`. The second column is the referencing column for\nthe foreign key. This means there is a row, `pk_id=4`, for which a parent\nprimary key doesn't exist. You can decide if these\nkeys are valid and if they are not, you can delete them."]]