Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select ORDER BY column and RAND() both?

Hello dear friends.

mysql_query("SELECT id FROM tb_table ORDER BY num ASC, ORDER BY RAND() LIMIT 1");

is this coding correct? I want to find all rows ASC num and there can be 1000 rows that num is 1 another 1000 that num is 2. But I want it to sort ASC like 1s firstly and choose one of them randomly.

like image 655
pzztzz Avatar asked Oct 27 '11 18:10

pzztzz


People also ask

How do I sort by both ASC and DESC in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Can we use two ORDER BY in same query?

After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name). You can modify the sorting order (ascending or descending) separately for each column.

How does ORDER BY work with multiple columns?

If you specify multiple columns, the result set is sorted by the first column and then that sorted result set is sorted by the second column, and so on. The columns that appear in the ORDER BY clause must correspond to either column in the select list or columns defined in the table specified in the FROM clause.

Can we sort multiple columns by ORDER BY clause in a single query?

To sort the records in descending order, use the DESC keyword. Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first.


1 Answers

You only need to specify ORDER BY once.

mysql_query("SELECT id FROM tb_table ORDER BY num ASC, RAND() LIMIT 1");
like image 155
Joe Stefanelli Avatar answered Sep 19 '22 21:09

Joe Stefanelli