Search code examples
mysqlsqlsortinground-robin

sort by MySQL special group


Table A shows results that I have by running the following SQL in MySQL.

SELECT * FROM table 
WHERE MATCH (title) AGAINST ('marka tv')

Table A

enter image description here

Table B shows results that I want to get. As you can see the groups are in round-robin order.

Table B

enter image description here


Solution

  • If I understand the question, you want to sort the output so the groups are in a round-robin fashion rather than ordered. You can do this by enumerating the values within each group and then using that information for sorting:

    SELECT t.*
    FROM (SELECT t.*,
                 (@rn := if(@g = groups, @rn + 1,
                            if(@g := groups, 1, 1)
                           )
                 ) as rn
          FROM table t CROSS JOIN
               (SELECT @rn := 0, @g := '') params
          WHERE MATCH (title) AGAINST ('marka tv')
          ORDER BY groups
         ) t
    ORDER BY rn, groups;