How can I store the output of a query into a temporary table and use the table in a new query?

江枫思渺然 提交于 2020-01-13 05:00:28

问题


I have a MySQL query which uses 3 tables with 2 inner joins. Then, I have to find the maximum of a group from this query output. Combining them both is beyond me. Can I break down the problem by storing the output of the first complicated query into some sort of temporary table, give it a name and then use this table in a new query? This will make the code more manageable. Thank you for your help.


回答1:


This is very straightforward:

CREATE TEMPORARY TABLE tempname  AS (    
    SELECT whatever, whatever
      FROM rawtable
      JOIN othertable ON this = that
)

The temporary table will vanish when your connection closes. A temp table contains the data that was captured at the time it was created.

You can also create a view, like so.

CREATE VIEW viewname AS (    
    SELECT whatever, whatever
      FROM rawtable
      JOIN othertable ON this = that
)

Views are permanent objects (they don't vanish when your connection closes) but they retrieve data from the underlying tables at the time you invoke them.



来源:https://stackoverflow.com/questions/22260257/how-can-i-store-the-output-of-a-query-into-a-temporary-table-and-use-the-table-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!