sql-order-by

Ordering by the order of values in a SQL IN() clause

淺唱寂寞╮ 提交于 2019-11-25 22:37:44
问题 I am wondering if there is away (possibly a better way) to order by the order of the values in an IN() clause. The problem is that I have 2 queries, one that gets all of the IDs and the second that retrieves all the information. The first creates the order of the IDs which I want the second to order by. The IDs are put in an IN() clause in the correct order. So it\'d be something like (extremely simplified): SELECT id FROM table1 WHERE ... ORDER BY display_order, name SELECT name, description

SQL multiple column ordering

大憨熊 提交于 2019-11-25 22:30:57
问题 I am trying to sort by multiple columns in SQL, and in different directions. column1 would be sorted descending, and column2 ascending. How can I do this? 回答1: ORDER BY column1 DESC, column2 This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal. 回答2: The other answers lack a concrete example, so here it goes: Given the following People table: FirstName | LastName | YearOfBirth -----

MySQL: Alternatives to ORDER BY RAND()

六眼飞鱼酱① 提交于 2019-11-25 22:05:55
问题 I\'ve read about a few alternatives to MySQL\'s ORDER BY RAND() function, but most of the alternatives apply only to where on a single random result is needed. Does anyone have any idea how to optimize a query that returns multiple random results, such as this: SELECT u.id, p.photo FROM users u, profiles p WHERE p.memberid = u.id AND p.photo != \'\' AND (u.ownership=1 OR u.stamp=1) ORDER BY RAND() LIMIT 18 回答1: UPDATE 2016 This solution works best using an indexed column . Here is a simple

PostgreSQL sort by datetime asc, null first?

女生的网名这么多〃 提交于 2019-11-25 21:59:18
问题 I need to sort a PostgreSQL table ascending by a date/time field, e.g. last_updated . But that field is allowed to be empty or null and I want records with null in last_updated come before non-null last_updated . Is this possible? order by last_updated asc /* and null last_updated records first ?? */ 回答1: Postgres provides the NULLS FIRST | LAST keywords for the ORDER BY clause to cater for that need exactly: ... ORDER BY last_updated NULLS FIRST A typical use case is with descending sort

Multiple “order by” in LINQ

女生的网名这么多〃 提交于 2019-11-25 21:56:25
问题 I have two tables, movies and categories , and I get an ordered list by categoryID first and then by Name . The movie table has three columns ID, Name and CategoryID . The category table has two columns ID and Name . I tried something like the following, but it didn\'t work. var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name }) 回答1: This should work for you: var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name) 回答2: Using non-lambda, query-syntax LINQ, you can do this