对行进行排序以平均分配公用记录

时间:2019-01-09 12:10:20

标签: mysql sql

我有一个包含以下数据的表:

+----+-------+---------+
| id | name  | country |
+----+-------+---------+
|  1 | alice | usa     |
|  2 | bob   | usa     |
|  3 | chad  | russia  |
|  4 | derek | china   |
|  5 | ethan | usa     |
+----+-------+---------+

sql中是否有任何方法可以对我的表重新排序(除ORDER BY RAND()外),这将允许我以这样的方式显示记录,即每行连续显示一个唯一的国家/地区。也就是说,如果前一行也包含国家“美国”,请在尽可能长的时间内显示与其他国家/地区的记录。

在上述情况下,可能的输出之一可能是:

+----+-------+---------+
| id | name  | country |
+----+-------+---------+
|  1 | alice | usa     |
|  3 | chad  | russia  |
|  2 | bob   | usa     |
|  4 | derek | China   |
|  5 | ethan | usa     |
+----+-------+---------+

我基本上是在尝试分布行,以便在大多数记录具有相同的支配值的情况下,它们看起来更加分散。

1 个答案:

答案 0 :(得分:1)

有些人为的,也许...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,name VARCHAR(12) NOT NULL UNIQUE
,country VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1,'alice','usa'),
(2,'bob','usa'),
(3,'chad','russia'),
(4,'derek','china'),
(5,'ethan','usa'),
(6,'fred','usa');

SELECT id,name,country FROM (SELECT *, @i:=@i+1 i FROM my_table,(SELECT @i:=0) vars ORDER BY country = 'usa') a ORDER BY MOD(i,4), id;
+----+-------+---------+
| id | name  | country |
+----+-------+---------+
|  2 | bob   | usa     |
|  3 | chad  | russia  |
|  5 | ethan | usa     |
|  4 | derek | china   |
|  6 | fred  | usa     |
|  1 | alice | usa     |
+----+-------+---------+
6 rows in set (0.00 sec)

正在查看评论,看来您真正要寻找的是这样的东西...

SELECT x.* 
  FROM my_table x 
  JOIN my_table y 
    ON y.country = x.country 
   AND y.id <= x.id 
 GROUP 
    BY x.id 
 ORDER 
    BY COUNT(*), country;
+----+-------+---------+
| id | name  | country |
+----+-------+---------+
|  4 | derek | china   |
|  3 | chad  | russia  |
|  1 | alice | usa     |
|  2 | bob   | usa     |
|  5 | ethan | usa     |
|  6 | fred  | usa     |
+----+-------+---------+