我奇怪的SubSelect,需要LEFT JOIN改进

时间:2014-01-15 17:56:16

标签: mysql sql

以下是一个示例SQL转储:https://gist.github.com/JREAM/99287d033320b2978728

  • 我有一个抓取一捆用户的SELECT。
  • 然后我执行foreach循环将所有关联的tree_processes附加到该用户。
  • 所以我最终做X查询:用户*树。

将两者一起取出会不会更有效率?

  • 我考虑过做LEFT JOIN Subselect,但我很难把它弄清楚。
  • 下面我已经完成了在SELECT中选择正确数据的查询,但是我必须对所有15行执行此操作,这似乎是可怕浪费内存。< / LI>

这是我的肮脏的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

1 个答案:

答案 0 :(得分:1)

在LEFT JOIN中,您使用'fresh'作为表别名。在您选择此选项时,您需要另外说明您想要的列。由于只需要添加一列(id):

freshness.id

到select子句。

左连接的ON子句看起来也很狡猾。也许fresh.id = ss.subscribers_id?

干杯 -