0

我只想查询 table2 中包含“课程”值的条目,并且 table1 中不存在“课程”。我最初根据“课程”值将 table1 内部连接到 table2。这是我到目前为止所拥有的,但它不起作用:

    $query = "SELECT value1,value2,value3 FROM table2 INNER JOIN table1 USING(course)
            WHERE table2.sem = '$semester' AND NOT EXISTS (SELECT course FROM table1)
            ORDER BY course";
    $result = mysql_query($query2) or die(mysql_error());

    while ($row2 = mysql_fetch_array($result))
    {
        print_r($row);echo "<br><br>";
    }

此内部连接代码有效:

    $query = "SELECT * FROM table1 INNER JOIN table2 USING(course) 
            WHERE table1.sem = '$semester'
            ORDER BY course";
    $result = mysql_query($query) or die(mysql_error());
4

2 回答 2

3
$query = "SELECT value1,value2,value3 FROM table2 
            WHERE table2.sem = '$semester' AND course IS NOT NULL
            AND course NOT IN(SELECT course FROM table1)
            ORDER BY course";

编辑:如果您想深入解释为什么要走这条路线而不是左连接(这也可以),请查看这篇文章:

http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/

于 2012-07-26T15:55:30.217 回答
2
SELECT value1,value2,value3 
FROM table2 t2
LEFT JOIN table1 t1 ON t2.course = t1.course
WHERE t1.course IS NULL
  AND t2.sem = '$semester'
ORDER BY course"; 
于 2012-07-26T16:00:57.923 回答