简体   繁体   中英

Select rows does not match in one table(mysql)

How Can I query mysql and select rows which does not match my query ? currently this is my sql If I want to select rows which match :

SELECT `user_id`
FROM `my_table`
WHERE `my_table`.`month` >= '201510'
AND `my_table`.`month` <= '201601'

In mysql this would select user_ids

what I want is to select user_ids where they don't have any record, a broken sql would be :

SELECT `user_id`
FROM `my_table`
WHERE `my_table`.`month` !>= '201510'
AND `my_table`.`month` !<= '201601'

to be more clear, mongo has a nice $not variable which perform a logical operation, I want something like $not but in mysql(or mariadb)

Simply use NOT BETWEEN -

SELECT `user_id`
FROM `my_table`
WHERE `my_table`.`month` NOT BETWEEN '201510' AND '201601'

In case of one value -

`my_table`.`month` <> '201510'

Try this:

SELECT user_id
FROM my_table
WHERE month NOT BETWEEN '201510' AND '201601'

One more solution:

SELECT `user_id`
FROM `my_table`
WHERE `my_table`.`month` < '201510'
AND `my_table`.`month` > '201601'

This is equivalent to ( answered by @sougata ):

SELECT `user_id`
FROM `my_table`
WHERE `my_table`.`month` NOT BETWEEN '201510' AND '201601'

You need to check the column for NULL value explicitly

SELECT *
FROM `my_table`
WHERE `my_table`.`month` NOT BETWEEN '201510' AND '201601'
   OR `my_table`.`month` IS NULL

because every comparison with a NULL value will return NULL. And NULL is neither TRUE nor FALSE.

A general answer for your question

select rows which does not match my query

Encapsulate your query and use it in an 'NOT IN' clause

SELECT `user_id`
FROM `my_table`
WHERE `user_id` NOT IN (
    SELECT `user_id`
    FROM `my_table`
    WHERE `my_table`.`month` >= '201510'
    AND `my_table`.`month` <= '201601'
)

But that would usually be inefficient.

Surprisingly there is a way to reverse a condition the way, that NULL will be converted to TRUE:

IF (condition, 0, 1)

so your query could look like

SELECT `user_id`
FROM `my_table`
WHERE IF((`my_table`.`month` >= '201510' AND `my_table`.`month` <= '201601'), 0, 1)

It also works with

CASE WHEN condition THEN 0 ELSE 1 END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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