2

I'm building Mysql query:

select * from `table` order by field(`column`, "param1", "param2", "param3")

where param1, param2, param3 comes from JSON Array ["param1", "param2", "param3"] and when I put the parameters hardcoded in the query everything is OK, but when I prepare it (because I don't know what count and order is coming):

set json_array='["param1", "param2", "param3"]';
select * from `table` order by field(`column`, replace(replace(json_array, '[', ''), ']', ''))

Its not working.

1
  • This is going to be a tough one to answer. You may want to reference where you found your original documentation on how to do this, even if its not complete enough. I've googled it and not found anything directly related. Commented Feb 12, 2020 at 18:04

1 Answer 1

1

You have to use Prepared Statements

SET @json_array='["param3", "param1", "param2"]';
SET @query = CONCAT('select * from `table` order by field(`column`, ',
                    replace(replace(@param, '[', ''), ']', ')'));
PREPARE stmt1 FROM @query;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

DEMO

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

4 Comments

For me it doesn't work - sqlfiddle.com/#!9/0c738f/1 :-(
@iMarh I have found a solution for MySQL 5.7. Which version of MySQL do you use?
My version is 5.5. I see that 5.5 also works. Thanks Alberto!
@iMarh Happy to help. If this answer or any other one solved your issue, please mark it as accepted :)

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.