MySQL find_in_set function not work as expect

All we need is an easy explanation of the problem, so here it is.

Now I am using this command to query user_id not in collections, this is my sql:

select *
from report_user_foundation
where !FIND_IN_SET(user_id ,(
    select GROUP_CONCAT(login_user_ids) as bet_user_ids
    from report_summary rs 
    where statistic_time >= 1606752000000)
)

I query user id from table report_user_foundation that not in report_summary table login_user_ids column. but when the using the result user id to query in report_summary that still exists.

select login_user_ids 
from report_summary rs 
where login_user_ids like '%4685%'

Am I sql is not correct? Am I missing something?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

FIND_IN_SET ( GROUP_CONCAT ) — cleaver, but clunky. Instead of

select *
from report_user_foundation
where !FIND_IN_SET(user_id ,(
    select GROUP_CONCAT(login_user_ids) as bet_user_ids
    from report_summary rs 
    where statistic_time >= 1606752000000)
)

do

SELECT *
    FROM report_user_foundation AS rsf
    WHERE NOT EXISTS(
            SELECT 1 FROM report_summary
                   ON rsf.user_id = login_user_ids
                  AND statistic_time >= 1606752000000
                    )
   /* AND login_user_ids like '%4685%' */

or, alternatively,

SELECT rsf.*
    FROM report_user_foundation AS rsf
    LEFT JOIN report_summary rs
                   ON rsf.user_id = rs.login_user_ids
                  AND rs.statistic_time >= 1606752000000
    WHERE rs.id IS NULL
   /* AND login_user_ids like '%4685%' */

Alas, I don’t understand your comment about where login_user_ids like '%4685%'. Perhaps it goes where I put the comments.

If these tables get big, this composite index may help:

report_summary:  INDEX(login_user_ids, statistic_time)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply