Main Content

Delegate Question - defining MySQL table relationships as you create the tables

Archive - Originally posted on "The Horse's Mouth" - 2010-05-02 09:00:07 - Graham Ellis

Q - Can define how tables are linked (joined together) when you set them up in MySQL, rather than having to specify the join each time that you SELECT data from the tables?

What a great (and logical) idea, but it's not straightforward / automatically available. The current / default system in the basic MySQL is somewhat illogical, as what can join up to what really ought to be specified with the database definition, and not as the data is extracted ... where erroneous (and silly) joins can be specified, and furthermore the user of the data needs to understand its structure.

There are some tools / approaches which can help towards implementing a system - basically, you want to be able to specify the orange bits in the following when calling up data, and have the magenta bit always / automatically provided from design time:

Select f1, f2, f3, f4 from t1 left join t2 on f2 = f6 where f7 > 1000

Some things that may help:

Views - From release 5.0, MySQL has included views which allow you to define a VIEW onto your data, and such views may include JOINs (gets a bit tricky at UPDATE time); a joined view - especially in conjunction with Stored Procedures - will help towards your goal.

Stored Procedures - Again, from Release 5.0. You don't need to specify the full series of MySQL statements every time, but can store them to be run each time you press the "Green Button" to make a request. [stored procedure resources]

Frameworks such as Ruby on Rails - The "Model" element of frameworks such as Ruby on Rails (and others too) allow / encourage you to specify rather more details that you would normally present to MySQL, including the limits that need to be applied to data in certain fields, and relationships. [Ruby on Rails sample]

Encapsulation of data within objects - If you access your data / database through objects, you'll be getting the ability to encapsulate the JOIN so that it won't be visible to / the concern of the user of your class of objects

Libraries of valid joins - I've found it very useful to hold libraries of valid joins in certain applications, so that only sensible joins are performed. A single composite join if you have a lot of tables (one of our customer joined 27 tables!) can be inefficient - but a menu scheme which only allows things which have been predefined can work wonders. Table of allowed joins described fully [here] and available for you to try [here]