我如何在mysql中查询两个不同的表

时间:2015-05-27 04:02:45

标签: php mysql sql pdo

如何验证两个查询,如果第一个查询为NULL则继续第二个查询?

第一次查询:

 SELECT max(logs) as logs,id FROM table1 WHERE 
 message NOT LIKE "[ SYSTEM%"

第二次查询:

 SELECT max(logs) as logs,id FROM table2 WHERE 
 message LIKE "[ SYSTEM%"

3 个答案:

答案 0 :(得分:1)

我认为你应该看看你的解释。因为对db的查询计数较少 - 更好。在这种情况下,您应该使用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%"
;

按字段类型,您可以了解从哪个表接收数据。
但如果你的解释不好,你应该使用单独的查询:

<?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);

答案 1 :(得分:1)

这个查询看起来很难看,但我认为你可以做到这一点

(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%")

您可以想象,如果仅使用一个查询而不是两个查询,我们可以更快地获取记录。

你也可以在结果中添加标志(只是为了检查表1或表2中的记录)

答案 2 :(得分:0)

   $query1 = "SELECT max(logs) as logs,id FROM table1 WHERE 
 message NOT LIKE '[ SYSTEM%'";
$query2 = SELECT max(logs) as logs,id FROM table2 WHERE 
 message LIKE '[ SYSTEM%'";
if(mysql_query($query1)) {
    $result = mysql_query($query1);
} else {
   $result = mysql_query($query2);
}