Search code examples
phpmysqlsqljointemp-tables

How to do a MySQL query without creating temp tables?


I have a bit of a situation here.

I have a query:

SELECT DISTINCT (testrecurring.id), testrecurring.cxl, testci.cd
FROM testci, testrecurring 
WHERE (testci.id = testrecurring.id) 
AND testci.x_origin='1' 
ORDER BY testrecurring.id DESC;

Now, if a var is not set, I need to do a select on this query, and here is the catch. I need to exclude some id's. Here is how I'm doing it now.

I create a table with that query: create table xxx SELECT * ..... and now the results from my previous query are inside another table called xxx.

Then:

if (!isset($var)) {
    $delete = mysql_query("delete from xxx USING xxx, future_recurring where xxx.id = future_recurring.id");
}

and after the records have been deleted I do my final select * from xxx.

This works just fine, the only thing is that I need to redo all this logic by not creating any tables. Maybe doing some joins, I'm not sure how to proceed.

I hope this is not very confusing.

Any ideas?


Solution

  • And now how about this?:

    SELECT tr.id, tr.cxl, tci.cd
    FROM testci AS tci 
    INNER JOIN testrecurring AS tr
        ON tci.id = tr.id
    LEFT OUTER JOIN future_recurring AS fr
        ON tr.id = fr.id
    WHERE tci.x_origin='1' 
        AND fr.id IS NULL
    GROUP BY tr.id, tr.cxl, tci.cd
    ORDER BY tr.id DESC
    

    This only includes results in which the testrecurring.id is NOT FOUND in future_recurring