How to mix ASC and RANDOM() on SQLite ORDER BY

2019-09-15 02:20发布

问题:

So, I'm facing an error while trying to use ORDER BY for 2 columns:

... ORDER BY val, random();

Error is: "2nd ORDER BY term does not match any column in the result set"

I tried different ways to combine ASC sorting for 1st column and random sorting for second column, no luck.

UPDATED to provide more info

CREATE TABLE tabela ( id INTEGER, val TEXT, PRIMARY KEY(id) );

INSERT INTO tabela (val) VALUES ('paid');
INSERT INTO tabela (val) VALUES ('paid');
INSERT INTO tabela (val) VALUES ('paid');
INSERT INTO tabela (val) VALUES ('standard');
INSERT INTO tabela (val) VALUES ('standard');
INSERT INTO tabela (val) VALUES ('standard');
INSERT INTO tabela (val) VALUES ('standard');
INSERT INTO tabela (val) VALUES ('standard');

Expected sample result:

val        id
---        ---
paid       3
paid       1
paid       2
standard   5
standard   8
standard   4
standard   6
standard   7

where 'id' 1,2,3 will be randomly sorted within 'paid' 'val' and 'id' 4 ... 8 will be randomly sorted within 'standard' 'val'

回答1:

select val, id from (select random() as r, * from tabela) order by val, r;

The trick is to make an on-the-fly table (inside the (...)) which has a column with random values. It is possible to order by that.
Note that this query is sorting/ordering complete rows of that on-the-fly table.

Output 1:

paid|1  
paid|3  
paid|2  
standard|8  
standard|5  
standard|7  
standard|6  
standard|4  

Output 2:

paid|3  
paid|1  
paid|2  
standard|5  
standard|8  
standard|7  
standard|4  
standard|6  

Please excuse my impression that you think of ordering columns. It might help you to see the difference, if you use only the subquery in the (...), study the output and then imagine "manually" sorting the rows, while not being allowed to change any of the rows.

This is the query making the on-the-fly table (with additional ordering):

select random() as r, * from tabela order by val, id;  

And its output:

6112298175921944810|1|paid  
-750320757383183987|2|paid  
-4687754812847362857|3|paid  
574487853771424670|4|standard  
6662074554381494613|5|standard  
5947282373212186891|6|standard  
-695595223160523440|7|standard  
-6914056362765123037|8|standard