繁体   English   中英

SQL查询排除值

[英]SQL Query Excluding value

我有一个查询,要在其中排除特定值(在此示例中为“垫子”)

该查询在没有子查询的情况下完美运行:

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
  FROM test
  LEFT JOIN test2
  ON test.noID=test2.noID
  WHERE test.SAME = 555 and test.Name NOT IN (
                                              SELECT *
                                              FROM test
                                              WHERE test.NAME = "Mat"
                                              )
  group by SAME , name
  order by same desc  

这里的例子:

http://www.sqlfiddle.com/#!2/1f1fb/28

如果要将确切名称与Mat匹配,则可以执行以下操作:

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
  FROM test
  LEFT JOIN test2
  ON test.noID=test2.noID
  WHERE test.SAME = 555 and test.Name != "Mat"

group by SAME , name
  order by same desc 

如果要排除所有包含Mat的内容,则:

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
      FROM test
      LEFT JOIN test2
      ON test.noID=test2.noID
      WHERE test.SAME = 555 and test.Name NOT LIKE '%Mat%'

    group by SAME , name
      order by same desc 

如果要排除以Mat开头的内容,则:

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
          FROM test
          LEFT JOIN test2
          ON test.noID=test2.noID
          WHERE test.SAME = 555 and test.Name NOT LIKE 'Mat%'

        group by SAME , name
          order by same desc 

您可以使用NOT LIKE 语句

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
  FROM test
  LEFT JOIN test2
  ON test.noID=test2.noID
  WHERE test.SAME = 555 and test.Name not like 'Mat'
  group by SAME , name
  order by same desc

SQLFiddle

<>!= 运算符

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
  FROM test
  LEFT JOIN test2
  ON test.noID=test2.noID
  WHERE test.SAME = 555 and test.Name <> 'Mat'
  group by SAME , name
  order by same desc

SQLFiddle

您的查询应为:-

SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
  FROM test
  LEFT JOIN test2
  ON test.noID=test2.noID
  WHERE test.SAME = 555 and test.Name NOT IN (
                                          SELECT NAME
                                          FROM test
                                          WHERE test.NAME = "Mat"
                                          )
  group by SAME , name
  order by same desc

子查询将不起作用,因为您在子查询中给了select *,但是在外部查询中,只有一个要匹配的列是test.Name。 如果您可以将子查询放入(SELECT test.Name FROM test WHERE test.NAME =“ Mat”)之类的子查询中,则整个查询都可以使用。 但顺便说一下,这里不需要子查询本身即可获得所需的结果。

暂无
暂无

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

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