MySQL NOT IN from another column in the same table

后端 未结 5 2049
天涯浪人
天涯浪人 2021-02-09 00:32

I want to run a mysql query to select all rows from a table films where the value of the title column does not exist anywhere in all the values of anot

5条回答
  •  感情败类
    2021-02-09 01:09

    Have you tried using NOT EXISTS:

    SELECT * 
    FROM films f1
    WHERE NOT EXISTS (SELECT collection 
                      FROM films f2
                      WHERE f1.title = f2.collection);
    

    See SQL Fiddle with Demo

    If you want to use IN then you will want to look for values that are NOT NULL:

    SELECT * 
    FROM films 
    WHERE title NOT IN (SELECT collection 
                        FROM films
                        WHERE collection is not null);
    

    See SQL Fiddle with Demo

    The result for both is:

    | ID |  TITLE |   COLLECTION |
    ------------------------------
    |  2 | Film 1 |       (null) |
    |  3 | Film 2 | Collection 1 |
    

    The problem with your current query is that -- stealing from @Quassnoi's answer here:

    Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

    Since the null value is being returned by your subquery you want to specifically exclude it.

提交回复
热议问题