Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

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?

like image 474
Suleman Ahmad Avatar asked Mar 22 '13 07:03

Suleman Ahmad


1 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')
like image 143
Yogesh Suthar Avatar answered Oct 23 '22 20:10

Yogesh Suthar