Where Clause Woes in Stored MySQL Query
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 kno开发者_运维知识库w how to do this with two separate queries, but the question is whether this is possible with only one query?
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.
精彩评论