2015-05-27 17 views
7

come posso convalidare due query, se la prima query è NULL procedere alla seconda query?Come posso interrogare due tabelle diverse in mysql

prima query:

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

seconda query:

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

Si può usato per controllare mysqli_num_rows no. di righe restituite dalla prima query. –

+1

forse usa un 'UNION' e usa un' SELECT' esterno con un 'LIMIT 1' – Sean

+0

if (! $ Result) {// fai qualcosa} – Andrew

risposta

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); 
} 
1

Penso che si dovrebbe guardare al vostro spiegare. Perché meno contare le query su db - meglio. In questo caso è necessario utilizzare l'unione:

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%" 
; 

per tipo di campo è possibile capire da quale tabella si ricevono i dati.
Ma se il vostro spiegare sarà male, si consiglia di utilizzare query separate:

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

Questa query sembra brutto, ma penso che si può fare

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

Potete immaginare come più veloce possiamo ottenere i record se usato solo una query invece di due.

è anche possibile aggiungere bandiera risultato (solo per controllare se il record dalla tabella 1 o tabella 2)

+0

come aggiungere un flag? :) –

+0

SELECT max (logs) come logs, id, 'I AM TABLE 2' AS 'which_table' FROM table2 ... dovresti aggiungerlo anche per la tabella 1 – parveen

Problemi correlati