我对SQL不太满意,并希望做一些我认为相当简单的事情。以下查询返回一列的一列ID:
select distinct(email_campaign_id)
from hubspot.email_events a
where a.subject in ('subject1', 'subject2', 'subject3')
我想在另一个查询中使用此列ID,如下所示:
with relevant_ids as
(
select distinct(email_campaign_id)
from hubspot.email_events a
where a.subject in ('subject1', 'subject2', 'subject3')
)
select *
from hubspot.email_events a
where a.email_campaign_id in relevant_ids
然而这会引发错误:
ERROR: syntax error at or near "relevant_ids"
我在这里做错了什么?我使用'with'是不正确的?
答案 0 :(得分:2)
只需:
select *
from hubspot.email_events a
where a.email_campaign_id in (
select distinct(email_campaign_id)
from hubspot.email_events a
where a.subject in ('subject1', 'subject2', 'subject3')
)
如果你想使用CTE,你必须在没有指定列名的情况下在CTE中命名列,但在你的情况下,它很好,如:
with relevant_ids as
(
select distinct(email_campaign_id) --as COLUMNNAME
from hubspot.email_events a
where a.subject in ('subject1', 'subject2', 'subject3')
)
select *
from hubspot.email_events a
where a.email_campaign_id in (SELECT COLUMNNAME from relevant_ids)
答案 1 :(得分:1)
您必须在var_dump
:
SELECT
查询
IN
答案 2 :(得分:1)
或者只是加入你的cte
with relevant_ids as
(
select distinct(email_campaign_id)
from hubspot.email_events a
where a.subject in ('subject1', 'subject2', 'subject3')
)
select *
from hubspot.email_events a
join relevant_ids ri on ri.email_campaign_id = a.email_campaign_id