假设我有以下表格。
create table t1 (id INT, tempData varchar(25));
和数据
insert into t1 values
(01, 'value 01'),
(02, 'value 02'),
(03, 'value 03'),
(04, 'value 04'),
(05, 'value 05'),
(06, 'value 06'),
(07, 'value 07'),
(08, 'value 08'),
(09, 'value 09'),
(10, 'value 10'),
(11, 'value 11'),
(12, 'value 12');
现在我想要的是创建一个查询以下面的格式获取数据
+++++++++++++++++
Id + tempData
+++++++++++++++++
03 + value 03
09 + value 09
01 + value 01
// now random order except above three ids
04 + value 04
06 + value 06
.
.
.
+++++++++++++++++
我想要第一行为03,然后是09,然后是01,然后是任意随机顺序。
有关如何完成此操作的任何建议吗?
我有庞大的数据库,订购我有大约1200个ID。所以我不能手动编写。还有其他方法我可以说数字为3,9,1
吗?
答案 0 :(得分:1)
select * from t1 order by (id = 3) desc, (id = 1) desc, (id = 9) desc, rand();
另外,谢谢你的小提琴;很少有人问SQL问题,或者懒得制作一个。
发布信息:
模式:
create table t2 (prio INT PRIMARY KEY, t1_id INT);
insert into t2 values (3, 3), (2, 1), (1, 9);
查询:
select t1.*
from t1
left join t2 on t1.id = t2.t1_id
order by t2.prio desc, rand();
答案 1 :(得分:0)
试试这个:
ORDER BY
CASE id
WHEN 3 THEN -3
WHEN 9 THEN -2
WHEN 1 THEN -1
ELSE 0
END, Rand();
更新1:请改为尝试:
SELECT t1.*
FROM t1
LEFT JOIN
(
SELECT -1 sortorder, 3 ID
UNION ALL
SELECT -2, 9
UNION ALL
SELECT -3, 1
) t2 ON t1.ID = t2.ID
ORDER BY t2.sortorder DESC, Rand();
答案 2 :(得分:0)
试试这个ORDER BY -
SELECT
*
FROM
t1
ORDER BY
CASE id WHEN 3 THEN -3 WHEN 9 THEN -2 WHEN 1 THEN -1 ELSE RAND() END
CREATE TABLE t2(id INT PRIMARY KEY AUTO_INCREMENT, sort_id INT);
INSERT INTO t2 VALUES(NULL, 3),(NULL, 9),(NULL, 1);
SELECT t1.*, t2.* FROM t1
LEFT JOIN t2
ON t1.id = t2.sort_id
ORDER BY IFNULL(t2.id - 100000000, RAND())
... 100000000用于省略MAX(id)。