0

Here is my SQL query:

SELECT `main_bid`,`main_plan` FROM `business` 
order by FIELD(`main_plan`,'Diamond','Platinum','Gold','Listed')

I want to display first Diamond values randomly then platinum values randomly and so on.

I know there is a rand() MySQL function to get random results from tables. But i don't know how to use it when there is already one MySQL FIELD() function.

Sample data:

main_bid main_plan
------------------
   1      Diamond
   2      Diamond
   3      Diamond
   1      Platinum
   2      Platinum
   3      Platinum
   1      Gold
   2      Gold
   3      Gold

I need output as:

main_bid main_plan
------------------
   3      Diamond
   1      Diamond
   2      Diamond
   2      Platinum
   1      Platinum
   3      Platinum
   2      Gold
   1      Gold
   3      Gold

or

main_bid main_plan
------------------
   3      Diamond
   2      Diamond
   1      Diamond
   1      Platinum
   3      Platinum
   2      Platinum
   3      Gold
   2      Gold
   1      Gold


    SELECT `main_bid`,`main_plan` FROM `business` 
    order by FIELD(`main_plan`,'Diamond','Platinum'),rand()

This query is shuffling all results. i have to shuffle Diamond results first and then Platinum.

2 Answers 2

1
SELECT main_bid, main_plan 
FROM business 
where main_plan in ('Diamond','Platinum')
order by case when main_plan = 'Diamond' then 1
              when main_plan = 'Platinum' then 2
         end,
         rand()
Sign up to request clarification or add additional context in comments.

4 Comments

its shuffling all results... i need first diamond results randomly..and then platinum randomly...your query shuffling all main_plan
Then add example data to your question and expected output.
Please add explanation on what the code actually does, even if for some it is obvious on first sight.
can u check my question again...??
0

Try this query instead of using FIELDS()

SELECT `main_bid`,`main_plan`,case  
     when main_plan = "Diamond" then "1" 
     when main_plan = "Platinum" then "2" 
     when main_plan = "Gold" then "3"
     end as plan_type  FROM `business` 
     order by plan_type,RAND()

3 Comments

your answer won't work when i there is more than 2 values in my column...But still thanks for help..
@user2530951 Please check my updated query,This may help you.I think
This has been automatically flagged as low-quality. Perhaps you should add some explanation about what your code does exactly, or your answer could be deleted by the community.

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.