如何在表中查找不在其他表中的行

时间:2013-11-16 07:30:52

标签: php mysql sql

我有两张桌子:

  1. staticip有两列:ipstaticipid

  2. rm_users有很多列,其中一列是staticipcpe

  3. 我想在staticip表格中找到staticipid='2'中的ipstaticipcpe与表rm_users中的$sqls="select s.ip, s.staticipid from staticip s where s.staticipid='2' and not exists (select u.staticipcpe from rm_users u where u.staticipcpe=s.ip"; 不等。

    我尝试了以下sql语句,但它没有用。

    "Warning: mysql_result(): supplied argument is not a valid MySQL result resource"
    

    我有以下消息

    {{1}}

3 个答案:

答案 0 :(得分:1)

在其他可能的问题中,你错过了一个右括号:

$sqls="select s.ip, s.staticipid from staticip s 
        where s.staticipid='2' and not exists 
        (select u.staticipcpe from rm_users u 
        where u.staticipcpe=s.ip)";

此外,the mysql_* functions are deprecated。使用MySQLi或PDO。

答案 1 :(得分:1)

如果您的查询是正确的,您可以使用NOT IN Clause来实现您的目标

Select Id
From Test
Where Id Not In( Select Foo From Bar )

查看更多信息

MySQL "NOT IN" query

答案 2 :(得分:1)

根据您的数据库,JOIN可能优于子查询(请参阅Join vs. sub-query),我也支持反引号(Importance of backtick around table name in MySQL query):

SELECT `s`.`ip`,`s`.`staticipid`
FROM `staticip` AS `s`
INNER JOIN `rm_users` AS `u`
ON `u`.`staticipcpe`<>`s`.`ip`
WHERE `s`.`staticipid`='2';

用简单的英语:

  • SELECT:从结果中获取字段“ip”和“staticipid”
  • FROM:主表格为“staticip” - 别名为“s”
  • INNER JOIN:将“staticip”中的行与“rm_users”中的行进行比较
  • ON(INNER JOIN的一部分):从“rm_users”
  • 获取“ip”中“staticipcpe”未列在“staticipcpe”字段下的行
  • WHERE:过滤结果,使“staticipid”的值必须为“2”

不要忘记考虑索引字段rm_users.staticipcpestaticip.staticipid(我假设这个已经是PRIMARY KEY)和staticip.ip,否则你正在查看完整的表格扫描,而不是从内存中利用MySQL的b树查找。