我正在尝试执行以下MySQL SELECT语句,以获取针对每个父机会ID执行的上一个活动的日期。
将从4个表中检索活动列表:呼叫,会议,任务,电子邮件。
当我添加条件“XXXXX.parent_id = opportunities.id”(在内部4子SELECTS中)时,我收到语法错误。
如果我删除“XXXXX.parent_id = opportunities.id”,则会执行这些语句(当然,结果与我想要的结果无关)。
以下是我尝试的代码:
SELECT
opportunities.id,
opportunities.name,
(
SELECT MAX(`last_activity_date`) FROM
(
SELECT c.date_end AS `last_activity_date`
FROM calls AS c
WHERE c.parent_type = 'Opportunities'
AND c.parent_id = opportunities.id
AND c.status IN ('Held')
AND c.deleted = '0'
UNION
SELECT m.date_end
FROM meetings AS m
WHERE m.parent_type = 'Opportunities'
AND m.parent_id = opportunities.id
AND m.status IN ('Held')
AND m.deleted = '0'
UNION
SELECT t.date_due
FROM tasks AS t
WHERE t.parent_type = 'Opportunities'
AND t.parent_id = opportunities.id
AND t.status IN ('Completed')
AND t.deleted = '0'
UNION
SELECT e.date_sent
FROM emails AS e
WHERE e.parent_type = 'Opportunities'
AND e.parent_id = opportunities.id
AND e.status IN ('sent', 'archived')
AND e.deleted = '0'
) AS `activities`
) AS "opportunities_activities"
FROM opportunities
WHERE opportunities.deleted = '0'
ORDER BY opportunities.id ASC
答案 0 :(得分:0)
您不能在内部嵌套查询中使用外部查询字段,因为每个内部查询必须独立于任何外部查询。
尝试下面的查询以获得所需的结果。
SELECT
opportunities.id,
opportunities.name,
(
SELECT MAX(`last_activity_date`) FROM
(
SELECT c.date_end AS `last_activity_date`
FROM calls AS c
join opportunities o on c.parent_id = o.id
WHERE c.parent_type = 'Opportunities'
AND c.status IN ('Held')
AND c.deleted = '0'
UNION
SELECT m.date_end
FROM meetings AS m
join opportunities o on m.parent_id = o.id
WHERE m.parent_type = 'Opportunities'
AND m.status IN ('Held')
AND m.deleted = '0'
UNION
SELECT t.date_due
FROM tasks AS t
join opportunities o on t.parent_id = o.id
WHERE t.parent_type = 'Opportunities'
AND t.status IN ('Completed')
AND t.deleted = '0'
UNION
SELECT e.date_sent
FROM emails AS e
join opportunities o on e.parent_id = o.id
WHERE e.parent_type = 'Opportunities'
AND e.status IN ('sent', 'archived')
AND e.deleted = '0'
) AS `activities`
) AS "opportunities_activities"
FROM opportunities
WHERE opportunities.deleted = '0'
ORDER BY opportunities.id ASC