2013-11-28 59 views
0

正如標題所說,我可以預先定義一些結果集在MySQL(因爲它是從內部級別到外部級別進行評估)並在查詢中稍後重用它們嗎?是否可以在MySQL中預定義查詢?

我在這裏有一個例子查詢(不要被尺寸被嚇):

SELECT id, globalId, date, serverId, gamemodeId, mapId FROM 
     (
      (SELECT * FROM 
      (
       SELECT 
       ll.id AS id, ll.globalId AS globalId, ll.date AS date, ll.serverId AS serverId, ll.gamemodeId AS gamemodeId, ll.mapId AS mapId, origin 
       FROM 
       (
         (SELECT id, globalId, date, serverId, playerId, 'playerjoins' AS origin 
         FROM playerjoins pj 
         WHERE playerId = 976) 
        UNION ALL 
         (SELECT id, globalId, date, serverId, playerId, 'playerleaves' AS origin 
         FROM playerleaves pl 
         WHERE playerId = 976) 
        ORDER BY date DESC 
       ) pjl 
       JOIN levelsloaded ll 
       ON pjl.date <= ll.date 
       GROUP BY ll.id 
       ORDER BY ll.date DESC 
      ) above 
      WHERE origin = 'playerjoins') 
     UNION ALL 
      (SELECT * FROM 
       (
        SELECT 
        ll.id AS id, ll.globalId AS globalId, ll.date AS date, ll.serverId AS serverId, ll.gamemodeId AS gamemodeId, ll.mapId AS mapId, origin 
        FROM 
        (
          (SELECT id, globalId, date, serverId, playerId, 'playerjoins' AS origin 
          FROM playerjoins pj 
          WHERE playerId = 976) 
         UNION ALL 
          (SELECT id, globalId, date, serverId, playerId, 'playerleaves' AS origin 
          FROM playerleaves pl 
          WHERE playerId = 976) 
         ORDER BY date DESC 
        ) pjl 
        JOIN levelsloaded ll 
        ON pjl.date >= ll.date 
        GROUP BY ll.id 
        ORDER BY ll.date DESC 
       ) below 
      WHERE origin = 'playerleaves') 
     ) total 
     ORDER BY date DESC 

我想以某種方式預定義pjl

  (
        (SELECT id, globalId, date, serverId, playerId, 'playerjoins' AS origin 
        FROM playerjoins pj 
        WHERE playerId = 976) 
       UNION ALL 
        (SELECT id, globalId, date, serverId, playerId, 'playerleaves' AS origin 
        FROM playerleaves pl 
        WHERE playerId = 976) 
       ORDER BY date DESC 
      ) pjl 

我使用它在兩次我的完整查詢。我正在查詢 pjl = (...)開頭的圖像,然後在其餘代碼中,您可以使用pjl。它應該只對查詢的生命週期有效。

例如,如果在PHP/MySQL設置中使用多行查詢(使用;)定義它,我可以看到發生了一些問題。

+4

也許你需要一個看法? – fthiella

+0

@fthiella然而,與查詢相比,視圖有效的時間更長。我擔心它會對業績產生負面影響。 – skiwi

+0

好吧...所以你不希望你的子查詢被評估兩次? – fthiella

回答

相關問題