MySQL JOIN on an arbitrary number of tables with independent WHERE clauses -


I am creating a complex search application with a large number of potential inputs, each input is optional. I am trying to create a query in a modular fashion.

Let's say I have two separate questions, each with a free WHERE terms:

  select from * T1 Where T1C1 = x SELECT * FROM T2 WHERE T2.c1 = y   

I should have the following code valid:

  SELECT * to T1 INNER T2 ON t1.c2 = t2.c2 WHERE t1.c1 = x and t2.c1 = y   

However, since WHERE conditions are grouped together at the end , It would be very difficult to apply in a modular fashion, so I tried to do it: SELECT * t1 join WHERE t1.c1 = x INNER t1.c2 = t2.c2 WHERE t2.c1 = y

However, this code is invalid independent What is the best way to join an arbitrary number with the WHERE section?

can be conditionally applied to join the tables - and where < / Code> Sections are finally included - like:

  SELECT * FROM t1 Inner G2T1 G1T2C2 = T2C2 IN3 GenT3O1T1 N3C3 = T3C3 Inner Teen On T4 On T1C4 = T4c4 Where T1C1 = X & T2C2 = Y and T3C3 = Z and T4 C4 = a   

and you can construct it as a string conditionally, the basis on which The user chooses on

While the / code> section and join may work dynamically, there may be some bad problems for it.

First of all, it should still be custom when inserted, for example, for t3 only t2 and t1 Can not be connectable. You have the same problems with the where section, each table should be customized based on the columns in the column.

In other words, it is not possible that this problem is completely generalized, in the end you will need to shift the custom SQL which will depend on the particular table. Worse, the table will change over time, and SQL has to be replaced with it. If you are building complex SQL dynamically, you can set yourself up for maintenance headache.

In addition, as your app grows, you want to tune the SQL for each combination to optimize the query. Make sure you try to make it in this form.

Comments