从子查询选择中选择字段

时间:2018-04-19 09:23:15

标签: sql postgresql

我有这个查询只是从ad_media获取字段,但我无法弄清楚如何选择子查询选择中的字段以及左边的字段与ad_params连接 任何帮助,谢谢你

select ad_media.ad_media_id
, ad_media.ad_id 
from ad_media 
where ad_media.ad_id in
(
    select action_states.ad_id 
    from action_states 
    where action_states.state = 'reg'   
    and action_states.action_id = '1' 
    and action_states.timestamp::date between '2018-04-17' and '2018-04-17' 
    and action_states.ad_id in
    (
        select ads.ad_id 
        from ads  
        where ads.category = '2010' 
        and ads.name = 'joe'
    ) 
)  
left join ad_params 
on ad_media.ad_id = ad_params.ad_id;

2 个答案:

答案 0 :(得分:1)

您可以尝试使用isAuthenticated()代替inner join

subquery

答案 1 :(得分:0)

如果没有看到您的数据,很难说如何以最佳方式编写查询,但根据您的评论中收集的信息,这可能会很有效:

select ad_media.ad_media_id
, ad_media.ad_id 
, ads.* --or pick whatever individual fields from ads that you want
from ad_media 
inner join ads
    on ads.ad_id = ad_media.ad_id
    and ads.category = '2010' 
    and ads.name = 'joe'
left join ad_params 
    on ad_media.ad_id = ad_params.ad_id
where exists
(
    select 1
    from action_states 
    where action_states.state = 'reg'   
    and action_states.action_id = '1' 
    and action_states.timestamp::date between '2018-04-17' and '2018-04-17'  
    and action_states.ad_id = ad_media.ad_id
);

注意:可以通过多种方式编写此查询以产生您所追求的结果;但最佳表现取决于每个表中的数据量,数据的外观(即我们根据每个条件筛选出多少记录),以及表中存在哪些索引。