Question

Lets say I have table as below.

create table t1 (id INT, tempData varchar(25));

and data as

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');

Now what I want is create a query to get data in below format

+++++++++++++++++
Id  + tempData
+++++++++++++++++
03  + value 03
09  + value 09
01  + value 01
// now random order except above three ids
04  + value 04
06  + value 06
.
.
.
+++++++++++++++++

I want first row as 03, then 09, then 01 and then any random order.

Any suggestion on how to get this done?

data at sqlfiddle


Edit 1

I have huge database and the for ordering I have around 1200 ids. So I can't write those manually. Is there any other way where I can say number as 3,9,1?

Was it helpful?

Solution

select * from t1 order by (id = 3) desc, (id = 1) desc, (id = 9) desc, rand();

Also, thank you for the Fiddle; too few people asking SQL questions know about it, or bother to make one.

post edit:

schema:

create table t2 (prio INT PRIMARY KEY, t1_id INT);

insert into t2 values (3, 3), (2, 1), (1, 9);

query:

select t1.*
from t1
left join t2 on t1.id = t2.t1_id
order by t2.prio desc, rand();

OTHER TIPS

Try this:

ORDER BY 
  CASE id
    WHEN 3 THEN -3
    WHEN 9 THEN -2
    WHEN 1 THEN -1
    ELSE 0
  END, Rand(); 

Update 1: Try this instead:

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();

SQL Fiddle Demo

Try this 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 is used to omit MAX(id).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top