I've got two MySQL queries that both insert data into a table. Both have the following format:
CREATE TABLE IF NOT EXISTS `data` (
`id` BIGINT NOT NULL AUTO_INCREMENT UNIQUE,
PRIMARY KEY (`id`)
)
SELECT `field1`, `field2`
WHERE `active` = 1
The only differences between the two queries are how field1
and field2
are determined, and some minor differences in the conditions clause. Both run up to 12K and more records.
Now, what will be more efficient:
A. Run both queries separately:
if (mysql_query($query1)) {
return mysql_query($query2);
}
return false;
B. OR combine the two queries with a UNION, and run once:
$query = 'SELECT `field1`, `field2` WHERE `active` = 1
UNION
SELECT DO_ONE(`field1`), DO_TWO(`field2`) WHERE `active` = 1
ORDER BY `field1`';
return mysql_query('CREATE TABLE IF NOT EXISTS `data` (
`id` BIGINT NOT NULL AUTO_INCREMENT UNIQUE,
PRIMARY KEY (`id`)
) ' . $query)
The data from the one query is useless without the data from the other, so both need to succeed. DO_ONE
and DO_TWO
are user defined MySQL functions that change the field data according to some specs.