Sort by order of values in a select statement “in” clause in mysql

后端 未结 4 879
挽巷
挽巷 2020-11-28 07:24

I\'m selecting a set of account records from a large table (millions of rows) with integer id values. As basic of a query as one gets, in a sense. What I\'m doing us build

4条回答
  •  自闭症患者
    2020-11-28 08:14

    You're first query surely uses an order by clause. So, you could just do a join, and use the same order by clause.

    For example, if this was your first query

    SELECT customer_id
      FROM customer  
     WHERE customer_id BETWEEN 1 AND 100 
    ORDER
        BY last_name
    

    And this was your second query

    SELECT inventory_id
      FROM rental
     WHERE customer_id in (...the ordered list...)
    

    Combined would be

    SELECT r.inventory_id
      FROM rental r
    INNER
      JOIN customer c
        ON r.customer_id = c.customer_id    
     WHERE c.customer_id BETWEEN 1 AND 100 
    ORDER
        BY c.last_name
    

提交回复
热议问题