views:

37

answers:

2

Say I have 3 queries. Query 1 returns a piece of information that Query 2 and Query 3 needs. Is there a way for Query 2 and Query 3 to access this piece of information from the result of Query 1?

Right now, I have Query 1 executing twice: once in Query 2 and once in Query 3. This doesn't seem efficient to me.

Is there a better way in MySQL?

EDIT 1:

For example, say Query 1 returns this:

    Id
   ====
    1
    3
    7

Now, Query 2 and Query 3 need 1, 3, 7 in their individual WHERE clauses.

A: 

Assuming:

query1: select id from foo;
query2: select * from bar where id = #value#;

You could just write query2 like this:

select * from bar where id in (select id from foo);

You might have a problem if items are being added to foo between you running the two queries.

mlathe
This is the way the OP is already running the queries.
Noah Goodrich
A: 

You can eliminate the possibility of the result set changing by using a serializable transaction. Most databases support these; MySQL does if you use the InnoDB storage engine. Before issuing the first query issue a

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

command. When you have completed all the statements, ROLLBACK; .

See here for more details... http://dev.mysql.com/doc/refman/5.1/en/set-transaction.html

Brian Hooper