从数据库表中获取最后一条和第一条记录的替代方法

时间:2015-12-22 13:26:32

标签: mysql sql select query-optimization union

SELECT * FROM
    (SELECT * FROM customer ORDER BY customer_id ASC  LIMIT 1 )DUMMY_ALIAS1
UNION ALL 
SELECT * FROM
    ( SELECT * FROM customer  ORDER BY customer_id DESC LIMIT 1)DUMMY_ALIAS11

获取最后和第一条记录的其他替代方法是什么,我认为我的查询未经过优化

2 个答案:

答案 0 :(得分:3)

您的查询很好,没有任何问题,但您可以稍微简化一下:

(SELECT * FROM customer ORDER BY customer_id ASC LIMIT 1)
UNION ALL
(SELECT * FROM customer  ORDER BY customer_id DESC LIMIT 1)

没有必要使用外部查询和别名,但不要忘记在customer_id上添加索引:

alter table customer add index idx_customer_id (customer_id);

或(可能更好,但这取决于上下文)将其定义为主键:

alter table customer add primary key (customer_id);

这将使您的查询得到优化。

答案 1 :(得分:1)

试试这个:

SELECT c.* 
FROM customer c
INNER JOIN ( SELECT MIN(customer_id) AS minCustomerId, 
                    MAX(customer_id) AS maxCustomerId 
             FROM customer
           ) AS b ON c.customer_id IN (minCustomerId, maxCustomerId);