how can i validate two queries, if the first query is NULL proceed to second query?
1st query:
SELECT max(logs) as logs,id FROM table1 WHERE
message NOT LIKE "[ SYSTEM%"
2nd query:
SELECT max(logs) as logs,id FROM table2 WHERE
message LIKE "[ SYSTEM%"
Required - SQL query to get records from multiple tables using Join. Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. First create a table in MySQL using following script and insert two records.
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.
I think you should look to your explain. Because less count queries to db - better. In this case you should use union:
SELECT max(logs) as logs, id, 'table1' type
FROM table1 WHERE message NOT LIKE "[ SYSTEM%"
UNION
SELECT max(logs) as logs, id, 'table2' type
FROM table2 WHERE message LIKE "[ SYSTEM%"
;
by field type you can understand from which table you receive data.
But if your explain will be bad, you should use separate queries:
<?php
$dbh = new PDO('mysql:dbname=test;host=127.0.0.1', 'root');
$sth = $dbh->prepare('
SELECT max(logs) as logs, id
FROM table1 WHERE message NOT LIKE :like
');
$sth->bindParam(':like', $like, PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
$sth = $dbh->prepare('
SELECT max(logs) as logs, id
FROM table2 WHERE message LIKE :like
');
$sth->bindParam(':like', $like, PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
}
var_export($result);
This query looks ugly, but I think you can do it
(SELECT max(logs) as logs,id
FROM table1
WHERE message NOT LIKE "[ SYSTEM%")
UNION ALL
(SELECT max(logs) as logs,id
FROM table2
WHERE message LIKE "[ SYSTEM%")
You can imagine how faster we can get the records if used only one query instead of two.
you can also add flag in result (just to check if record from table 1 or table 2 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With