I’d like to select all the rows from a temporary table that have a value equal to the maximum value.
TEMPORARY TABLE test
id | value
1 | 7
2 | 6
3 | 7
Expected result:
id | value
1 | 7
3 | 7
I’ve already tried several things but all attempts (except creating another temporary table with the same content) failed so far because of “You cannot refer to a TEMPORARY table more than once in the same query.” (Source: http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html).
Is there a possibility to do this in a more “elegant” way than copying the table and its contents?
What I’ve tested so far:
SELECT table1.* FROM test table1 LEFT JOIN test table2 ON table1.value < table2.value
WHERE table2.value IS NULL;
SELECT * FROM test WHERE value = (SELECT MAX(value) FROM test);
And this is my current solution:
CREATE TEMPORARY TABLE test2 (...);
INSERT INTO test2 SELECT * FROM test;
SELECT * FROM test WHERE value = (SELECT MAX(value) FROM test2);
You could try using variables. The following will scan the test table only once (not-tested):