views:

69

answers:

1

What I'd like to do is execute a MySQL query containing a where clause ("result query") that is stored in a column in the database. This column, containing the query, is a result of another query ("original query").

The catches:

  • The result query's where clause can contain a variable value (or two)
  • I don't know what the result query will be when executing the original query, so I cannot pass along the variable's value

(The list of result queries as well as the variables in the where clauses will be defined by me, so I will will have a list of all the possible variables.)

Essentially, I need to be able to correlate that variable with any number of other values, one example: a user_id, within the database.

original_query_table      | result_query_table
--------------------------------------------------------------
other_id result_query_id  | result_query_id  result_query
1        1                  1                "SELECT ... WHERE user_id = :id "   

I know how to do this with two separate queries, but the question is whether this is possible with only one query?

+1  A: 

I would do something like this:

SELECT 'select * from table_a where col_a = ?' INTO @query, 1 into @param1 FROM dual;
PREPARE stmt FROM @query;
EXECUTE stmt USING @param1 ;

So converting that into your tables, I guess would look like:

SELECT a.result_query INTO @query, b.result_query_id INTO @param1 FROM result_query_table a, original_query_table b where a.result_query_id = b.result_query_id;
PREPARE stmt FROM @query;
EXECUTE stmt USING @param1 ;

Will you know how many parameters the where clause will need? If that's dynamic, then things could get a bit tricky.

Andrew Dyster
Unfortunately, that is the issue. I don't know how many parameters it will need. Sometimes it's 1, sometimes it's 3. I'm not set on the table structure though, if changing that helps?
munch
So this answer helped me on another issue I was having. You deserve the credit for it. Don't spend all the points in one place :P
munch