MySQL SQL 查询其中字段不包含 $x
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/232935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Query Where Field DOES NOT Contain $x
提问by zuk1
I want to find an SQL query to find rows where field1 does not contain $x. How can I do this?
我想找到一个 SQL 查询来查找 field1 不包含 $x 的行。我怎样才能做到这一点?
回答by Vegard Larsen
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
这是一个什么样的领域?IN 运算符不能与单个字段一起使用,但旨在用于子查询或预定义列表:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIKE operator (but this will be slow):
如果您正在搜索字符串,请使用 LIKE 运算符(但这会很慢):
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
如果您限制它以便您搜索的字符串必须以给定的字符串开头,则它可以使用索引(如果该字段上有索引)并且速度相当快:
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
回答by Greg
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(确保事先正确转义 $x 以避免 SQL 注入)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
编辑:NOT IN
做一些不同的事情 - 你的问题不完全清楚所以选择使用哪个。 LIKE 'xxx%'
可以使用索引。 LIKE '%xxx'
或LIKE '%xxx%'
不能。