简体   繁体   English

如何使用PHP / mySQL查询一个表而不是另一个表中的条目?

[英]How to query entries that exist in one table and not the other using PHP/mySQL?

I want to query only the entries in table2 which contains a "course" value and "course" does not exist in table1. 我只想查询table2中包含“ course”值的条目,而table1中不存在“ course”。 I initially inner joined table1 to table2 based on the "course" value. 我最初根据“课程”值将table1内联到table2。 Here's what I have so far, which doesn't work: 这是我到目前为止无法使用的内容:

    $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>";
    }

This inner join code works: 此内部联接代码有效:

    $query = "SELECT * FROM table1 INNER JOIN table2 USING(course) 
            WHERE table1.sem = '$semester'
            ORDER BY course";
    $result = mysql_query($query) or die(mysql_error());
$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";

EDIT: If you want an in depth explanation as to why to go this route instead of the left join (which will also work) check out this article: 编辑:如果您想深入解释为什么要走这条路线而不是左联接(这也将起作用),请查看本文:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM