我有这样的表...
declare -a input=('alpha' 'beta' 'gama');
alpha="cow"
beta="goat"
gama="crow"
for i in "${input[@]}"
do
echo $(eval "echo $i") [this is wrong logic]
done
如何得到随机输出:
╔═════╦════════╦═════════════╗
║ id ║ text ║ parent_id ║
╠═════╬════════╬═════════════╣
║ 1 ║ test ║ 1 ║
║ 2 ║ asd ║ 1 ║
║ 3 ║ dsa ║ 1 ║
║ 4 ║ fgh ║ 4 ║
║ 5 ║ jkl ║ 4 ║
║ 6 ║ kkk ║ 4 ║
║ 7 ║ asas ║ 7 ║
╚═════╩════════╩═════════════╝
或
╔═════╦════════╦═════════════╗
║ id ║ text ║ parent_id ║
╠═════╬════════╬═════════════╣
║ 4 ║ fgh ║ 4 ║
║ 5 ║ jkl ║ 4 ║
║ 6 ║ kkk ║ 4 ║
║ 7 ║ asas ║ 7 ║
║ 1 ║ test ║ 1 ║
║ 2 ║ asd ║ 1 ║
║ 3 ║ dsa ║ 1 ║
╚═════╩════════╩═════════════╝
等......
答案 0 :(得分:0)
SELECT *
FROM Table1
ORDER BY parent_id * rand()
答案 1 :(得分:0)
根据@sagi的ans略微更新,附加组的行顺序保证。
这是演示。
-- data
create table tbl(id int, text char(20), parent_id int);
insert into tbl values
(1 , 'test', 1 ),
(2 , 'asd', 1 ),
(3 , 'dsa', 1 ),
(4 , 'fgh', 4 ),
(5 , 'jkl', 4 ),
(6 , 'kkk', 4 ),
(7 , 'asas', 7 );
select * from tbl;
select t.*
from tbl t inner join
(select parent_id, rand() rand_val from tbl group by parent_id) r
USING(parent_id)
order by rand_val, id;
mysql> select t.* from tbl t inner join (select parent_id, rand() rand_val from tbl group by parent_id) r USING(parent_id) order by rand_val, id;
+------+------+-----------+
| id | text | parent_id |
+------+------+-----------+
| 7 | asas | 7 |
| 4 | fgh | 4 |
| 5 | jkl | 4 |
| 6 | kkk | 4 |
| 1 | test | 1 |
| 2 | asd | 1 |
| 3 | dsa | 1 |
+------+------+-----------+
7 rows in set (0.00 sec)
mysql> select t.* from tbl t inner join (select parent_id, rand() rand_val from tbl group by parent_id) r USING(parent_id) order by rand_val, id;
+------+------+-----------+
| id | text | parent_id |
+------+------+-----------+
| 4 | fgh | 4 |
| 5 | jkl | 4 |
| 6 | kkk | 4 |
| 1 | test | 1 |
| 2 | asd | 1 |
| 3 | dsa | 1 |
| 7 | asas | 7 |
+------+------+-----------+
7 rows in set (0.00 sec)
答案 2 :(得分:0)
您可以使用子查询来完成此操作,类似于Juan解决方案:
SELECT s.* FROM YourTable s
INNER JOIN (select parent_id,max(rand()) as randVal FROM YourTable GROUP BY parent_id) t
ON(s.parent_id = t.parent_id)
ORDER BY t.randVal