2014-01-15 65 views
0

下面是一個簡單的SQL轉儲:https://gist.github.com/JREAM/99287d033320b2978728我的奇子查詢,需要一個LEFT JOIN改進

  • 我有一個選擇,抓住用戶的捆綁。
  • 然後我做一個foreach循環來將所有關聯的tree_processes附加到該用戶。
  • 所以我最終做X查詢:用戶*樹。

把它們放在一起會不會更高效?

  • 我想過做一個LEFT JOIN子選擇,但我很難讓它正確。
  • 下面我做了一個查詢來選擇SELECT中的正確數據,但是我必須爲所有15行執行此操作,並且它看起來像是浪費內存的TERRIBLE

這是我的髒Ateempt:

-

SELECT 
      s.id, 
      s.firstname, 
      s.lastname, 
      s.email, 
      (
       SELECT tp.id FROM tree_processes AS tp 
       JOIN tree AS t ON (
        t.id = tp.tree_id 
       ) 
       WHERE subscribers_id = s.id 
       ORDER BY tp.id DESC 
       LIMIT 1 
      ) AS newest_tree_id, 
      # 
      # Don't want to have to do this below for every row 
      (
       SELECT t.type FROM tree_processes AS tp 
       JOIN tree AS t ON (
        t.id = tp.tree_id 
       ) 
       WHERE subscribers_id = s.id 
       ORDER BY tp.id DESC 
       LIMIT 1 
      ) AS tree_type 


    FROM subscribers AS s 
    INNER JOIN scenario_subscriptions AS ss ON (
     ss.subscribers_id = s.id 
    ) 

    WHERE ss.scenarios_id = 1 
    AND ss.completed != 1 
    AND ss.purchased_exit != 1 
    AND deleted != 1 

    GROUP BY s.id 
    LIMIT 0, 100 

這是我LEFT JOIN嘗試,但我遇到麻煩SELECT值

SELECT 
     s.id, 
     s.firstname, 
     s.lastname, 
     s.email, 
     freshness.id, 
     # freshness.subscribers_id < -- Cant get multiples out of the LEFT join 


FROM subscribers AS s 
INNER JOIN scenario_subscriptions AS ss ON (
    ss.subscribers_id = s.id 
) 


LEFT JOIN (SELECT tp.id, tp.subscribers_id AS tp FROM tree_processes AS tp 
      JOIN tree AS t ON (
       t.id = tp.tree_id 
      ) 
      ORDER BY tp.id DESC 
      LIMIT 1) AS freshness 
ON (
    s.id = subscribers_id 
) 

WHERE ss.scenarios_id = 1 
AND ss.completed != 1 
AND ss.purchased_exit != 1 
AND deleted != 1 

GROUP BY s.id 
LIMIT 0, 100 
+0

請提供樣本數據集和預期輸出,因此我們不必對您的查詢進行逆向工程。 –

+0

這是一個轉儲:https://gist.github.com/JREAM/99287d033320b2978728 – JREAM

回答

1

在LEFT JOIN中,您使用「新鮮」作爲桌面別名。這在你選擇你需要另外說明你想從它的列(s)。由於只需要添加一列(id):

freshness.id 

到select子句。

你的左連接的ON子句看起來也很狡猾。也許freshness.id = ss.subscribers_id?

歡呼聲 -

+0

嘿謝謝,freshness.id工作。我更新了LEFT JOIN以表明我無法從新鮮獲取多個記錄。 – JREAM