使用MySQL临时表加速查询


  本文标签:MySQL临时表

  使用MySQL临时表,有时是可以加速查询的,下面就为您详细介绍使用MySQL临时表加速查询的方法,希望对您有所帮助  。

  把表的一个子集进行排序并创建MySQL临时表,有时能加速查询  。它有助于避免多重排序操作,而且在其他方面还能简化优化器的工作  。例如:

  1. SELECT cust.name,rcVBles.balance,……other columns  
  2.  
  3. SELECT cust.name,rcVBles.balance,……other columns  
  4.  
  5. FROM cust,rcvbles  
  6.  
  7. WHERE cust.customer_id = rcvlbes.customer_id  
  8.  
  9. AND rcvblls.balance>0  
  10.  
  11. AND cust.postcode>“98000”  
  12.  
  13. ORDER BY cust.name   

  如果这个查询要被执行多次而不止一次,可以把所有未付款的客户找出来放在一个临时文件中,并按客户的名字进行排序:

  1. SELECT cust.name,rcvbles.balance,……other columns  
  2.  
  3. SELECT cust.name,rcvbles.balance,……other columns  
  4.  
  5. FROM cust,rcvbles  
  6.  
  7. WHERE cust.customer_id = rcvlbes.customer_id  
  8.  
  9. AND rcvblls.balance>0  
  10.  
  11. ORDER BY cust.name  
  12.  
  13. INTO TEMP cust_with_balance   

  然后以下面的方式在临时表中查询: SELECT * FROM cust_with_balance

  WHERE postcode>“98000”
临时表中的行要比主表中的行少,而且物理顺序就是所要求的顺序,减少了磁盘I/O,所以查询工作量可以得到大幅减少  。

  注意:临时表创建后不会反映主表的修改  。在主表中数据频繁修改的情况下,注意不要丢失数据  。