簡體   English   中英

我奇怪的子選擇,需要左加入改進

[英]My Odd SubSelect, Need a LEFT JOIN Improvement

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

  • 我有一個SELECT,它可以吸引大量用戶。
  • 然后,我執行一個foreach循環,將所有關聯的tree_processes附加到該用戶。
  • 所以我最終做了X查詢: 用戶*樹。

一起獲取兩者會更有效嗎?

  • 我曾考慮過進行LEFT JOIN子選擇,但是我很難將其正確設置。
  • 下面,我進行了查詢以選擇SELECT中的正確數據,但是我將必須對所有15行執行此操作,這似乎是對內存的極大浪費。

這是我骯臟的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

在左聯接中,您使用“新鮮”作為表別名。 您在選擇中需要另外聲明要從中獲取的列。 由於只有一列(id),因此您需要添加:

freshness.id

選擇子句。

您的左聯接的ON子句看起來也很狡猾。 也許Fresh.id = ss.subscribers_id?

干杯-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM