2011-05-31 168 views
0

我將如何合併以下兩個sql select語句?合併兩個SQL SELECT語句返回來自兩個不同表的值

//select all rows from our userlogin table where the emails match 
$res1 = mysql_query("SELECT * 
         FROM userlogin 
         WHERE `email` = '".$email."'"); 
$num1 = mysql_num_rows($res1); 
//if the number of matchs is 1 
if($num1 == 1) { 
    //the email address supplied is taken so display error message 
    echo '<p class="c7">The <b>e-mail</b> address you supplied is already taken. Please go <a href="register.php">back</a> and try again.<br><img src="resources/img/spacer.gif" alt="" width="1" height="15"></p>'; 
    include_once ("resources/php/footer.php");   
    exit; 
} else { 
    //select all rows from our userlogin_fb table where the emails match 
    $res2 = mysql_query("SELECT * 
         FROM userlogin_fb 
         WHERE `email` = '".$email."'"); 
    $num2 = mysql_num_rows($res2); 
    //if the number of matchs is 1 
    if($num2 == 1) { 
    //the email address supplied is taken so display error message 
    echo '<p class="c7">The <b>e-mail</b> address you supplied is already taken. Please go <a href="register.php">back</a> and try again.<br><img src="resources/img/spacer.gif" alt="" width="1" height="15"></p>'; 
    include_once ("resources/php/footer.php");  
    exit; 
    } else {;} 

回答

3

用途:

//select all rows from our userlogin table where the emails match 
$query = sprintf("SELECT 1 
        FROM userlogin 
        WHERE `email` = '%s' 
        UNION ALL 
        SELECT 1 
        FROM userlogin_fb 
        WHERE `email` = '%s' ", 
        $email, $email); 
$res1 = mysql_query($query); 
$num1 = mysql_num_rows($res1); 
//if the number of matchs is 1 
if($num1 >= 1) { 
    //the email address supplied is taken so display error message 
    echo 'The <b>e-mail</b> address you supplied is already taken. Please go <a href="register.php">back</a> and try again.<br><img src="resources/img/spacer.gif" alt="" width="1" height="15"></p>'; 
    include_once ("resources/php/footer.php");   
    exit; 
} 
+0

非常感謝你! – methuselah 2011-05-31 06:01:34

+0

和UNION和UNION ALL之間的區別在於UNION ALL保留所有重複項。 – stivlo 2011-05-31 06:04:14

+0

@stivlo:是的,我剛剛爲Bjoem的回答留下了類似的評論。 UNION(全部或其他)在每個SELECT子句中也需要相同數量的列和數據類型。 'UNION ALL'比'UNION'快,因爲它不會刪除重複項。 – 2011-05-31 06:05:58

1

兩個做它(只是在SQL語句組成部分)的方式:

解決方案1:UNION

SELECT * 
FROM userlogin 
WHERE email = '$email' 
UNION 
SELECT * 
FROM userlogin_fb 
WHERE email = '$email'; 

兩個表基本上都需要相同字段,否則調整聲明的部分SELECT *

解決方案2:將錶鏈接到

SELECT * 
FROM userlogin AS T1 
JOIN userlogin_fb AS T2 ON T1.email = T2.email 
WHERE T1.email = '$email'; 

首先,我寧願(1),因爲(2)可能是由表設計的影響。

+0

'UNION'將刪除重複項,當'UNION ALL'不會 - 但我們也不知道這些表是完全相同的。和YUCK - 沒有ANSI-89連接語法;只有ANSI-92請。 – 2011-05-31 06:04:22

+0

更正了語法。 – Bjoern 2011-05-31 06:30:41