This might sound a bit un-realistic, but I’ve recently had to study the database structure of a system am maintaining remotely, and it hit me that there were some occassions when I wanted to find all columns that were linked to a given table (see, the original devs didn’t create explicit relations, but instead have relations encoded in the column names!).
For example, assuming all columns referring to a column parent.parent have the form table.somefield_parent as the means of documenting a relationship between the two fields, how do I find all such relationships (and the tables involved) using say the standard SQL commands / in-built functions?
Any solutions for MySQL or PostgreSQL are welcome.
NOTE :
- am not looking for patterns in the data, but in the meta-data.
- I know I can dump the db structure and search for the results there, but I don’t want to go out of the db-shell to find these relationships (assume am working in say psql, and don’t want to exit)
In PostgreSQL you can query the system catalog tables.
You can also query the information_schema, which consists of views providing the standard SQL way of displaying the information. Querying the system catalogs is usually much faster, though.
To find the children of one particular
parentcolumn:To find all related column according to the description:
This assumes that the parrent columns don’t have
_in the name.The key element is the join condition: