我正在尝试查找客户和客户从各种不同表格中共同拥有的所有IP数量。我知道在子查询中,最内层的查询无法访问最外层的查询,但我不确定如何连接表来解决这个问题。
非常感谢任何帮助。
表格订单是评论,company_user_role,previous_state_transitions
SELECT
r.id, r.state,
(SELECT count(dog.ip_address)
FROM
(SELECT DISTINCT ip_address COLLATE utf8_unicode_ci AS ip_address
FROM previous_state_transitions
WHERE user_id = r.user_id
UNION
SELECT DISTINCT ip_address COLLATE utf8_unicode_ci AS ip_address
FROM previous_state_transitions
WHERE state_machineable_id = r.user_id
AND state_machineable_type = "User"
UNION
SELECT DISTINCT ip_address
FROM reviews
WHERE user_id = r.user_id) AS dog
INNER JOIN
(SELECT DISTINCT ip_address COLLATE utf8_unicode_ci AS ip_address
FROM previous_state_transitions
WHERE user_id IN (SELECT user_id FROM company_user_roles WHERE company_id = r.company_id)
UNION
SELECT DISTINCT ip_address COLLATE utf8_unicode_ci AS ip_address
FROM previous_state_transitions
WHERE state_machineable_id = (SELECT user_id FROM company_user_roles WHERE company_id = r.company_id)
AND state_machineable_type = "User"
UNION
SELECT DISTINCT ip_address
FROM reviews
WHERE user_id = (SELECT user_id FROM company_user_roles WHERE company_id = r.company_id)) AS cat
ON dog.ip_address = cat.ip_address) AS ip_count_in_common
FROM reviews AS r
WHERE r.created_at > '2016-10-13'
ORDER BY 1 desc
答案 0 :(得分:0)
您的基本问题是在定义之前使用结果r
中的数据。
换句话说:您无法在构成r
的定义中引用最终结果r
。
您应该做的是从每个子查询开始,看看代码是否依赖于它。当它没有 - 如同引用r
的任何情况 - 你需要考虑一个不同的解决方案,例如在输出中返回user_id。
很抱歉,我只能给你一个解决问题的方法,而不是解决方案本身。和蒂姆一样,我试图为你编辑查询,但它太长了,我需要知道整个数据结构才能知道最佳解决方案。