SQL Query Where Field DOES NOT Contain $x

前端 未结 2 691
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 12:39

I want to find an SQL query to find rows where field1 does not contain $x. How can I do this?

相关标签:
2条回答
  • 2020-12-07 13:18

    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:

    -- 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):

    -- 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%';
    
    0 讨论(0)
  • 2020-12-07 13:32

    SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

    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.

    0 讨论(0)
提交回复
热议问题