以下是 SQL 转储示例:https://gist.github.com/JREAM/99287d033320b2978728
- 我有一个可以获取大量用户的 SELECT。
- 然后,我执行一个 foreach 循环,将所有关联的 tree_processes 附加到该用户。
- 所以我最终做了 X 查询:用户 * 树。
将两者一起获取不是效率更高吗?
- 我曾考虑过执行 LEFT JOIN Subselect,但很难正确执行。
- 下面我已经完成了一个查询,以在 SELECT 中选择正确的数据,但是我必须对所有 15 行执行此操作,这似乎是一种可怕的内存浪费。
这是我肮脏的尝试:
-
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
最佳答案
在 LEFT JOIN 中,您使用“freshness”作为表别名。在您选择时,您需要另外说明您想要从中获得哪些列。由于只有一列(id),您需要添加:
freshness.id
到 select 子句。
您的左连接 ON 子句看起来也很危险。也许 freshness.id = ss.subscribers_id?
干杯-
关于mysql - 我的奇怪子选择,需要 LEFT JOIN 改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21144832/