0

In my table is plenty of rows, I prepare test_result_table:

SELECT * FROM 
(
  SELECT ID, DATA
  FROM table
  WHERE DATA = "A" OR DATA = "B" OR DATA = "C"
) AS test_result_table

How I can do this:

SELECT * FROM
    (
        SELECT 1 AS RESULT, ID 
        FROM test_result_table
        WHERE DATA = "A"
      UNION  
        SELECT 2 AS RESULT, ID 
        FROM test_result_table
        WHERE DATA = "B"
      UNION
        SELECT 3 AS RESULT, ID 
        FROM test_result_table
        WHERE DATA = "C"
    ) AS result_id
ORDER BY RESULT

I know to do with temp table, is any better (faster) solution?

I expect (x = some ID):

RESULT |ID
1      |x
1      |x 
2      |x
2      |x
3      |x

1 Answer 1

1

You can get the same results by using the function FIND_IN_SET() which will return the value of the column RESULT:

SELECT t.*
FROM (
  SELECT 
    FIND_IN_SET(DATA, 'A,B,C') AS RESULT, 
    ID
  FROM tablename
) t
WHERE t.RESULT > 0
ORDER BY t.RESULT

See a simplified demo.
I can't tell about it's efficiency, but it surely is simpler.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for idea... it is 2time faster than my UNION over my 2mio rows

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.