I have a table whose primary key is referenced in several other tables as a foreign key. For example:
CREATE TABLE `X` (
`X_id` int NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`X_id`)
)
CREATE TABLE `Y` (
`Y_id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`X_id` int DEFAULT NULL,
PRIMARY KEY (`Y_id`),
CONSTRAINT `Y_X` FOREIGN KEY (`X_id`) REFERENCES `X` (`X_id`)
)
CREATE TABLE `Z` (
`Z_id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`X_id` int DEFAULT NULL,
PRIMARY KEY (`Z_id`),
CONSTRAINT `Z_X` FOREIGN KEY (`X_id`) REFERENCES `X` (`X_id`)
)
Now, I don't know how many tables there are in the database that contain foreign keys into X like tables Y and Z. Is there a SQL query that I can use to return:
- A list of tables that have foreign keys into X
- AND which of those tables actually have values in the foreign key
You can find all schema related information in the wisely named
information_schema
table.You might want to check the table
REFERENTIAL_CONSTRAINTS
andKEY_COLUMN_USAGE
. The former tells you which tables are referenced by others; the latter will tell you how their fields are related.Easiest:
1. Open phpMyAdmin
2. On the left click database name
3. On the top right corner find "Designer" tab
All constraints will be shown there.
I wrote a little bash onliner that you can write to a script to get a friendly output:
mysql_references_to:
So the execution:
mysql_references_to transaccion
(where transaccion is a random table name) gives an output like this:Listing all foreign keys in a db including description
restricting to a specific column in a table table
MySQL 5.5 Reference Manual: "InnoDB and FOREIGN KEY Constraints"
This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop constraint):
If you want to check tables in a specific database, add the following: