Domanda

Is it possible to query MySQL to determine a FK's CASCADE behavior? Currently I'm doing this:

SELECT
    COLUMN_NAME,
    REFERENCED_TABLE_NAME,
    REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
    TABLE_SCHEMA = 'my_db'
    AND
    TABLE_NAME = 'my_table'
    AND
    REFERENCED_COLUMN_NAME IS NOT NULL

This is great - it gives me almost all of the information I need to programmatically create similar FKs on clones of my_table. Unfortunately, INFORMATION_SCHEMA doesn't seem to have information on a FK's CASCADE behavior. Without getting into the specifics of why I need this information, I'd just like to know: is there some way to query for it?

EDIT - before people start suggesting it, CREATE TABLE LIKE ... won't work in my scenario, as far as copying FKs.

È stato utile?

Soluzione 2

Based on a suggestion in a comment by @Barmar (thanks!), here's what I ended up going with:

SELECT
    U.COLUMN_NAME,
    U.REFERENCED_TABLE_NAME,
    U.REFERENCED_COLUMN_NAME,
    C.UPDATE_RULE,
    C.DELETE_RULE
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
    ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
WHERE
    U.TABLE_SCHEMA = 'my_db'
    AND
    U.TABLE_NAME = 'my_table'
    AND
    U.REFERENCED_COLUMN_NAME IS NOT NULL

Which gives me everything I need to recreate the foreign keys properly:

+---------------------+-------------+-----------------------+------------------------+-------------+-------------+
| TABLE_NAME | COLUMN_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME | UPDATE_RULE | DELETE_RULE |
+---------------------+-------------+-----------------------+------------------------+-------------+-------------+
| my_table   | item_id     | item                  | id                     | CASCADE     | CASCADE     |
+---------------------+-------------+-----------------------+------------------------+-------------+-------------+

Altri suggerimenti

Knowing the name of the table, you could use the SHOW CREATE TABLE command to get the exact behavior of the constraint in question. You would then have to do some parsing, which would be more easily accomplished on the application side rather than in MySQL.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top