ORDER BY子句

ORDER BY常见的语法

  • ORDER BY 根据XX列进行排序, 在SELECT, WHERE, GROUP BY后面
  • LIMIT 一般放在最后, 与ORDER BY一起使用, 主要是对选择数量的限制
# ORDER BY
SELECT *
FROM customers
ORDER BY state DESC, first_name;

SELECT first_name, last_name
FROM customers
ORDER BY birth_date;

SELECT first_name, last_name, 10 AS points
FROM customers
ORDER BY points, first_name;
-- 尽量避免使用1, 2
SELECT first_name, last_name, 10 AS points
FROM customers
ORDER BY 1, 2;

-- Exercise
-- Get the order_items order_id=2, and total_price desc
SELECT *, quantity * unit_price AS total_price
FROM order_items
WHERE order_id = 2
ORDER BY (quantity * unit_price) DESC;

SELECT *, quantity * unit_price AS total_price
FROM order_items
WHERE order_id = 2
ORDER BY total_price DESC;

# LIMIT
SELECT *
FROM customers
LIMIT 3;
-- page 1: 1 - 3
-- page 2: 4 - 6
-- page 3: 7 - 9
# 前面是偏移量, 从XX开始查询3条数据
SELECT *
FROM customers
LIMIT 6, 3;
-- Exercise
-- GET the top three loyal customers
SELECT *
FROM customers
ORDER BY points DESC
LIMIT 3;
posted @ 2020-05-27 23:00  心远志高  阅读(474)  评论(0编辑  收藏  举报