2016-03-27 33 views
1

返回我有以下两个表删除行,如果它是由另一个查询

CREATE TABLE message_log 
(
    id integer, 
    message text, 
    from_id character varying(500), 
    to_id character varying(500), 
    match_id character varying(500), 
    own_account boolean, 
    reply_batch boolean DEFAULT false, 
    insert_time timestamp with time zone DEFAULT now() 
) 


CREATE TABLE likes 
(
    id integer, 
    userid character varying(500), 
    insert_time timestamp with time zone DEFAULT now() 
) 

我有以下查询,如果发送具有相同match_id没有消息,其中包含“@”返回match_ids。

select distinct(match_id) from message_log where own_account = TRUE and match_id not in 
(select match_id from message_log where message like '%@%') 

我也想返回to_ids,因为他们需要我要构造查询,所以我修改了查询

select distinct(match_id, to_id) from message_log where own_account = TRUE and match_id not in 
(select match_id from message_log where message like '%@%') 

现在我想创建一个查询,将删除任何行在喜欢的表格中,如果从上述查询返回的to_id与喜欢的表格中的userid匹配。是否可以在一个查询中做到这一点?

+0

'从...中删除where_to_id(select ...)'。但'独特'不是***功能。不要把列列表放在Postgres的圆括号里,它不会像你想象的那样。 –

回答

1

像这样的东西应该工作:

delete from b 
from (
    select distinct match_id, to_id 
    from message_log 
    where own_account = TRUE and match_id not in (select match_id from message_log where message like '%@%') 
) a inner join likes b on a.to_id = b.userid 

从本质上讲,只要把你的结果,并在您喜欢的表内连接来确定什么样的结果,从喜欢表中删除。

相关问题