Accessing a temporary table multiple times in MySql

前端 未结 4 1847
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 23:29

I have tried to use a temporary table as an intermediate result holder for a SELECT statement. The problem is though that I can\'t access the temp table multiple times in ot

4条回答
  •  终归单人心
    2021-01-13 00:11

    For this problem, where the temporary table is only to be read, I create a second temporary table as a copy of the first then use this in the query:

    CREATE TEMPORARY TABLE t2 as (SELECT * FROM dates_with_entries);
    

    Then

    SELECT 
    ...
    FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
    INNER JOIN project_times
        ON sub_result.datum = project_times.datum AND project_times.user_id = 20
    LEFT JOIN works AS w ON project_times.work_id = w.id
    LEFT JOIN sub_projects AS sp ON sp.id = w.sub_project_id
    LEFT JOIN projects AS p ON p.id = sp.project_id
    GROUP BY datum
    UNION(
        SELECT
          ..
      FROM (SELECT entrie_date AS datum FROM t2) AS sub_result
      INNER JOIN project_times AS pt ON pt.datum = sub_result.datum
      INNER JOIN works AS w on w.id = pt.work_id
      INNER JOIN sub_projects AS sp on w.sub_project_id = sp.id
      INNER JOIN projects AS p ON sp.project_id = p.id
      WHERE pt.user_id = 20
    ); 
    

提交回复
热议问题