Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i query two different tables in mysql

Tags:

sql

php

mysql

pdo

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%"
like image 520
argie cruz Avatar asked May 27 '15 04:05

argie cruz


People also ask

How can I get data from two tables in MySQL?

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.

How do I query between two tables in SQL?

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.


2 Answers

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);
like image 188
cn007b Avatar answered Oct 14 '22 06:10

cn007b


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 )

like image 27
parveen Avatar answered Oct 14 '22 08:10

parveen