0

I'm working with a database that contains a table called model_meta which contains metadata about all the various models in use by the application. Here is the relevant data structure:

CREATE TABLE model_meta (
  id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(64),
  oo INT(11),
  om INT(11),
  mo INT(11),
  mm INT(11),
  INDEX (name)
);

CREATE TABLE inventory (
  id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  type VARCHAR(255),
  customers_id INT(11)
);

CREATE TABLE customers (
  id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255),
  contact VARCHAR(255)
);

The columns oo, om, mo, and mm in the model_meta table contain a comma-separated list of ids to which that model has the specified relationship (i.e. one-to-one, one-to-many, etc.).

When a client requests data, all I'm given is the name of the table they're requesting (e.g. 'inventory') - from that, I need to determine what relationships exist and query those tables to return the appropriate result set.

Given a single variable (let's call it $input) that contains the name of the requested model, here are the steps:

  1. get model metadata: SELECT model_meta.* FROM model_meta WHERE model_meta.name = $input;

  2. determine which, if any, of the relationship columns (oo, om, mo, mm) contain values - keeping in mind that they can contain a comma-separated list of values.

  3. use the values from step 2 to determine the name of the related model(s) - for the sake of example, let's just say that only mo contains a value and we'll refer to it as $mo.

    So: SELECT model_meta.name FROM model_meta WHERE model_meta.id = $mo;

    Let's call this result $related.

  4. Finally, select data from the requested table and all tables that are related to it - keeping in mind that we may be dealing with a one-to-one, one-to-many, many-to-one, or many-to-many relationship. For this specific example:

    In psuedo-SQL: SELECT $input.*, $related.* FROM $input LEFT JOIN $related ON ($related.id = $input.$related_id);

This method uses three separate queries - the first to gather metadata about the requested table, the second to gather the names of related tables, and the third to query those tables and return the actual data.

My question: Is there an elegant way to combine any of these queries, reducing their number from from 3 to 2 - or even down to one single query?

The real goal, of course, is to in some way automate the retrieval of data from related tables (without the client having to knowing how the tables are related). That's the goal.

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • 1
    See [Is storing a delimited list in a database column really that bad?](http://stackoverflow.com/a/3653574) – eggyal Mar 05 '13 at 22:03
  • 1
    @eggyal Ah, fair enough - thanks for the link! But, for the sake of me learning new things, let's assume that the oo, om, mo, and mm columns can only contain a single value... – user1917012 Mar 05 '13 at 22:17

0 Answers0