检查值不在查询的另一个表中

时间:2013-01-20 00:32:33

标签: php mysql sql select

我环顾四周,似乎无法找到以下答案:

我想要做的就是运行一个SQL select语句,向用户显示提供发票号的东西(在这种情况下是唯一ID)没有显示在同一个数据库的另一个表中,而代码是如下:

$query = mysql_query("SELECT `ordate`, `invno` FROM `armast09` WHERE cshipno = '$username' AND `ordate` > DATE_SUB(CURDATE(), INTERVAL 4 DAY)") or die(header("location:index.php?e=4"));   
$numrows = mysql_num_rows($query);

$date = date('o-n-d');

include 'indexfiles/top.php';

    echo "The following deliveries are available for viewing / dispute:";
    echo "<br />";  
    echo "<br />";
    echo "<center>";
    echo "<table>"; 
        if($numrows != 0) {                 
            while ($info = mysql_fetch_array($query)) {
                echo "<tr>";                            
                    echo "<form action = \"deliverydispute.php?invno=".$info['invno']."\" method=\"POST\ onsubmit=\"return confirm('Are you sure you are ready to dispute? You can't go back after this.');\">";
                        echo "<td><b>Invoice Number: </b>".$info['invno']."</td>";
                        echo "<td><b>Order Date: </b>".$info['ordate']."</td>";                                 
                        echo "<td><a href = \"deliverydispute.php?invno=".$info['invno']."&&ordate=".$info['ordate']."\">Dispute</a></td>";
                    echo "</form>";                         
                echo "</tr>"; 
            }
        } else {
            echo ("<font color=\"red\" face=\"arial\" size=\"2\"><small>No orders are currently available for viewing.</small></font>");
        }
    echo "</table>";

2 个答案:

答案 0 :(得分:1)

您可以使用NOT IN谓词:

SELECT ordate, invno
FROM armast09
WHERE cshipno = '$username' 
  AND ordate > DATE_SUB(CURDATE(), INTERVAL 4 DAY) 
  AND invno NOT IN(SELECT invno FROM Anothertable WHERE invno IS NOT NULL);

LEFT JOIN

SELECT a.ordate, a.invno 
FROM armast09 a
LEFT JOIN anothertable a2 ON a.invno = a2.invno
WHERE a.cshipno = '$username' 
  AND a.ordate > DATE_SUB(CURDATE(), INTERVAL 4 DAY) 
  AND a.invno IS NULL;

答案 1 :(得分:0)

您可以通过以下方式轻松完成此操作:

SELECT X FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLEB.ID WHERE TABLEB.ID is null

应该这样做!