MYSQL如何根据店铺id混单

MYSQL How to order items mixed according to the shop id

我有一个table这样的。

+----+-----------+---------+
| id | product   | shop_id |
+----+-----------+---------+
|  1 | Product 1 |       1 |
|  2 | Product 2 |       3 |
|  3 | Product 3 |       2 |
|  4 | Product 4 |       3 |
|  5 | Product 5 |       1 |
|  6 | Product 6 |       2 |
+----+-----------+---------+

我想通过店铺编号订购。顺序应该是这样

Product 1 => Shop_id 1
Product 3 => Shop_id 2
Product 2 => Shop_id 3
Product 5 => Shop_id 1
Product 6 => Shop_id 2
Product 4 => Shop_id 3

我该怎么做?

SELECT x.*  
 FROM my_table x 
 JOIN my_table y 
   ON y.shop_id = x.shop_id 
  AND y.id <= x.id 
GROUP BY x.id 
ORDER 
   BY COUNT(*)
    , shop_id;

...或者,对于更大的数据集...

SELECT a.id
     , a.product
     , a.shop_id
  FROM 
     ( SELECT x.*
            , IF(shop_id = @prev,@i:=@i+1,@i:=1) i
            , @prev := shop_id 
         FROM my_table x
            , (SELECT @i:=1,@prev:='') vars 
        ORDER   
           BY shop_id
            , id
     ) a
 ORDER 
    BY i,shop_id;