MySql Finding a tree structure using Reference Keys - mysql

We have a parent table which stores the user details. Since now we were doing soft delete. However due to some legal commitments, we are forced to do a hard delete for the user details.
So the problem is the main table is referenced many places.
We could able to find all the referenced tables with the following query in MySQL
USE information_schema;
SELECT TABLE_NAME, Column_Name,Constraint_Name
FROM
KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'ProjectUser'
AND REFERENCED_COLUMN_NAME = 'userid'
AND TABLE_SCHEMA = 'testproduct';
It was a success as we got all tables around 45. However the real problem is, it is possible that the child table of "ProjectUser" also may referenced somewhere else.
For example,
one of the child table UserAddress is used as foriegn Key for some other table. How can I query to bring all the tables, which reference ProjectUser, and their child tables and grand child tables?

There is no query that's going to get you out of this mess. You can write a program to successively run queries to build this structure, but you will not be able to do it all in one query.
1) Use mysqldump, write something to parse the dump and build the tree
2) Use a tool to visualize the schema such as (schemaspy)[http://schemaspy.sourceforge.net/] or (mysql workbench)[http://www.mysql.com/products/workbench/]
3) Take #AlmaDo's suggestion seriously and add ON DELETE CASCADE. You can drop an existing foreign key and readd it using the later table function. If you have problems re adding the foreign key due to constraint violation, disable keys while you re add the foreign key.

Related

Is there a way to chek for foreign keys in MySql query browser?

How do i check if there is a foreign key between two tables in MySql Query browser?
The reason i need it, is because in order for Mysql Workbench to create a model containing all the connections, is through foreign keys, however, it shows no foreign key in any table.
So i'm left here wondering if the database was really built without any foreign keys (Which is actually possible) or if i'm doing something wrong. That's why i want to check in the Query browser.
There should be a Foreign Keys tab which should allow you to set or change the relationships.You can use this link to do this.
https://dev.mysql.com/doc/workbench/en/wb-table-editor-foreign-keys-tab.html
There's a tutorial here which should help you: http://jetgrill.blogspot.com/2009/05/how-to-add-foreign-key-in-mysql-query.html
You can query database metadata using the information schema.
Constraints can be queried using
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
You can add a where-clause to limit the result to the tables or relations you're interested in (TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME, ...)

Replacing one empty table with another table without affecting Foreign Keys in MySQL

I have migrated a database using structure only
In this database I have a table called hash that is empty, of course.
This table is being used by tons of other tables through foreign key.
I have another table called hash_copy that has been just copied from another database and is full of records (500'000 records).
I tried to replace one table by another with the following SQL Statement
SET FOREIGN_KEY_CHECKS=0;
RENAME TABLE hash to hash_empty, hash_copy to hash;
SET FOREIGN_KEY_CHECKS=1;
Problem is that now all my foreing keys are poiting to hash_empty which is what I was trying to avoid.
To sumup
I'd like to turn off Foreign Keys just to swap one table for another (throw the empty away and plug the full of records) without having to go through all the tables that makes references to it.
Is this possible?
Thanks in advance.
As per the comments, a table can be copied to another table like:
INSERT INTO hash SELECT * from hash_copy
More generally, the insert-select syntax works like as you would expect; you can specify column names (INSERT INTO hash(col1, col2, col3)) and include any SELECT syntax you normally would (functions, joins, where clauses, etc).

How do I see which columns throughout my database reference one particular column as a foreign key? Like a "reverse" foreign key?

I've got a pretty big relational database and am working on the admin backend. I want to know which tables reference a column in one particular table.
For example: let's say I've got a table products with id as the primary index. I can have a lot of tables that reference this index, such as an orders table, a user_bookmarks table, and a product_reviews table. If I want to delete a particular product, I first need to do some work with the other tables--a simple "cascade" or "delete" directive wouldn't be enough. How do I get MySQL to tell me exactly which columns in which tables are referencing the products.id index?
Bonus question: is there a built-in way to get this info using phpmyadmin?
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE (REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME) = ('mydatabase', 'products')
Re your comment:
MySQL doesn't support recursive queries, so unfortunately there's no way to find the complete graph of foreign keys in a single query. The best you could do is for each of the results of the above query, run the query again, substituting the TABLE_SCHEMA and TABLE_NAME as the string constants in the WHERE clause (be careful not to enter into infinite loops if you have circular foreign keys).
Could you not read the Schema from the database into MySQL Workbench, and then use the tool to plot out the relationships between the tables? I have not tried this myself, as I do the design in MySQL Workbench and then the mappings, etc... and then export to MySQL to create the database.

MySQL: How to find where a specific primary key is used as a foreign key in other tables?

I'm working on implementing a function to prevent removal of certain elements in a database (through the front end) if they have other items associated with them in other tables. Otherwise those other tables are looking for keys that aren't there.
If you understood that my hat is off to you.
I have many sets of tables to look through and need either a SQL query or a MySQL Workbench feature that can tell me, on entry of the primary key (column name, not actual value), if that key is used as a foreign key somewhere else.
Otherwise if anyone knows an offhand workaround, that would be great too!
SELECT
table_name, column_name
FROM
information_schema.key_column_usage
WHERE
referenced_table_name = '<table>'
and referenced_column_name = '<primary key column>'
A solution is described in this post to retrieve this information from information_Schema table.
1) If you want to work on these tables from your code, then fetch them as a container, for example ArrayList in your code and perform your logic.
2) If you want to work on these tables from your Stored Procedure, then use temporary tables to achive the same work you'd do in your java code through containers.

Determine InnoDB FK Constraints without information_schema

I'm writing some code to inspect a MySQL database structure, and need information about Foreign Key constraints (on InnoDB tables).
There are two ways I know of to do this:
Parse the results of SHOW CREATE TABLE X
Use INFORMATION_SCEMA.REFERENTIAL_CONSTRAINTS
Unfortunately option two requires MySQL 5.1.16 or later, so I can't use it unless/until I can convince our server guy to update, And while I can probably get away with option 1, it feels messy and without writing a full SQL parser I wouldn't feel sure my code would always work with any table.
Is there another way of getting at this information?
Thanks
From the MySQL 5.0 manual online:
You can also display the foreign key constraints for a table like
this:
SHOW TABLE STATUS FROM db_name LIKE 'tbl_name';
The foreign key constraints are listed in the Comment column of the
output.
Poster indicates that this doesn't provide ON UPDATE and ON DELETE information which is an important part of foreign key behavior.
Another option:
Since you control the code involved, is it possible to set up another MySQL instance in the same environment which is version 5.1+? If so, let's call that instance dummy. Run the SHOW CREATE TABLE on the live database. Then, on dummy run a DROP TABLE IF EXIST followed by the output from the SHOW CREATE TABLE query.
Now you can use INFORMATION_SCHEMA on the dummy database to get the information.