MySql - SubQuery is not working properly

1.3k views Asked by At

BubQuery always return the empty result if the query is correct.

1st Query:

SELECT * FROM `user` WHERE user_age IN(1,22,34);

Result:

enter image description here

2nd Query:

SELECT GROUP_CONCAT(user_age_list) AS user_age FROM `user_detail` WHERE id='1';

Result: enter image description here

I am try:

SELECT * FROM `user` WHERE user_age IN(SELECT GROUP_CONCAT(user_age_list) AS user_age FROM `user_detail` WHERE id='1');

Sqlfiddle: http://sqlfiddle.com./#!9/d6515f/3 //This is a sample table.

Above the query is always return the empty rows. But each of query return the result if its run single. Really I don't know where is the error. Please update the answer or suggest me.

2

There are 2 answers

11
Jaydip Jadhav On BEST ANSWER

Avoid Use of GROUP_CONCAT

SELECT * 
FROM `user` 
WHERE user_age IN(SELECT user_age_list FROM `user_detail` WHERE id='1');

UPDATED

SELECT * 
FROM `user` u 
WHERE EXISTS (SELECT 1 FROM `user_detail` ud  WHERE id='1' AND ud.user_age_list = u.user_age)
4
xQbert On
SELECT * 
FROM user
WHERE user_age IN 
(SELECT user_age_list user_age 
 FROM user_detail
 WHERE id='1');

You don't need the group concat here. The engine knows the result set is an inclusive list without the group concat.

What it is trying to do is compare the '1,22,34' to each user_age which is why you get no results.

1 <> '1,22,34'
22 <> '1,22,34'
34 <> '1,22,34' 

thus no results.