douou1872 2012-07-26 15:52
浏览 99
已采纳

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

I want to query only the entries in table2 which contains a "course" value and "course" does not exist in table1. I initially inner joined table1 to table2 based on the "course" value. 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());
  • 写回答

2条回答 默认 最新

  • douan7601 2012-07-26 15:55
    关注
    $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/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制