Home » Php » php – NOT IN Operator is not working for non-primary key values in mysql

php – NOT IN Operator is not working for non-primary key values in mysql

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have read many Q&A’s regarding NOT IN operator i.e
If I use IN operator to filter NULL values and white spaces It is not working Why?
and many others, But the problem is that when we use not in operator for non-primary key, it is not returning the response.

SELECT * FROM temp_customers WHERE temp_customers.fk_my_id NOT IN (SELECT fk_my_id FROM customers)

Where fk_my_id is non-primary key and might be a string.

Any Idea please?

How to&Answers:

use group_concat here for separating fk_my_id with comma

SELECT * FROM temp_customers WHERE temp_customers.fk_my_id NOT IN 
(SELECT GROUP_CONCAT(fk_my_id) FROM customers)   
# when fk_my_id is INTEGER output (1,2)

SELECT * FROM temp_customers WHERE temp_customers.fk_my_id NOT IN 
(SELECT GROUP_CONCAT("'",fk_my_id,"'") FROM customers)   
# when fk_my_id is VARCHAR output ('1','2')

Answer:

I my guess you have used wrong column in query: (SELECT fk_my_id FROM customers) . It should be pkId of your customer table

SELECT * FROM temp_customers 
WHERE temp_customers.fk_my_id 
NOT IN (SELECT pk_my_id FROM customers)