2

I want set a select list as variable and do some conditional check on it:
This is my code which is not working:

set @temp = (select docId from table_1);
SELECT 
   id,
   CASE when id IN (@temp) then 'TRUE' else 'FALSE' end as visited
FROM table_2;

Also tried this:

set @temp = (select docId from table_1);
SELECT 
   id,
   CASE when (FIND_IN_SET(id,@temp)=1) then 'TRUE' else 'FALSE' end as visited
FROM table_2;

In both case, visited column is coming FALSE for each row.

4
  • Why not simply do: select docId from table_1 Commented Apr 9, 2019 at 12:23
  • My actual code is different. I am using this feature to do some task. Have not written all the things over here. My main problem is coming in this task. The picture is very unclear that what happens exactly when i do set @variable. Commented Apr 9, 2019 at 13:03
  • You need to give more details, otherwise question seems very trivial atm. Commented Apr 9, 2019 at 13:04
  • @MadhurBhaiya Check now. Commented Apr 9, 2019 at 13:13

1 Answer 1

1

You can use LEFT JOIN with GROUP BY instead. Left joining may result in duplicate rows corresponding to table_2 (as there can be multiple rows for same id value in the table_1); to handle that, we will use Group By. Count() function can be used to determine if id exists in the table_1 or not, and accordingly determine TRUE/FALSE.

Try the following:

SELECT 
   t2.id,
   CASE WHEN t1.docId IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END AS visited
FROM table_2 t2
LEFT JOIN table_1 t1 ON t1.docId = t2.id 
Sign up to request clarification or add additional context in comments.

4 Comments

CASE WHEN t1.docId is not null THEN 'TRUE' ELSE 'FALSE' END AS visited..... is precisely working for me.
This count is merging all the rows into one , which is incorrect.
@lil-wolf it will group by on id so you will get one row per id. This is what your earlier query is also supposed to achieve. Unless your actual requirement is different.
But this count is giving me one row per 'whole table'. First comment is working for me. Left join will not duplicate the ids. anyway i am getting one row per id by left joining itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.