2016-03-27 32 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 

從本質上講,只要把你的結果,並在您喜歡的表內連接來確定什麼樣的結果,從喜歡錶中刪除。

相關問題