基于id和另一个布尔列计数的SQL查询

时间:2017-02-23 05:32:58

标签: sql postgresql

我有跟踪聊天消息日志的下表

CREATE TABLE public.perm_message_log
(
    id bigint NOT NULL DEFAULT nextval('perm_message_log_id_seq'::regclass),
    message text,
    from_id text,
    to_id text,
    match_id text,
    unix_timestamp bigint,
    own_account boolean,
    reply_batch boolean DEFAULT false,
    insert_time timestamp with time zone DEFAULT now(),
    account_id bigint,
    match_pk bigint
)

每个会话具有相同的match_id我想构建一个SQL查询,只有当reply_batch = true具有相同match_id的消息的message少于reply_batch时,才会返回match_ids p>

我希望我能够以清晰的方式写出来。

包含match_id的每一行都有reply_batch列,设置为true或false。我希望查询返回所有少于两个的delete from already_matched where already_matched.userid = ( WITH cte AS ( SELECT match_id FROM public.perm_message_log GROUP BY match_id HAVING SUM(CASE WHEN reply_batch THEN 1 ELSE 0 END) = 0 ) SELECT t1.from_id FROM public.perm_message_log t1 INNER JOIN cte t2 ON t1.match_id = t2.match_id WHERE NOT t1.own_account) " true" location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. # try_files $uri $uri/ =404; } 列的布尔值。

编辑@TimBiegeleisen

感谢您的回答,如果我要删除您的答案在另一个表中返回的行,该怎么办?我想出了下面的查询,但这是错误的。

jQuery('#deleteProj').submit(function() {
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
    var formData= jQuery(this).serialize();
    jQuery.ajax({
    url:ajaxurl,
    action:'function_name',
    data:formData,
    type: "POST",
    success: function(data) {
      // return
   }
   });
    return false; 
});

1 个答案:

答案 0 :(得分:1)

您可以尝试按match_id汇总表格,计算reply_batchmatch_id为真的次数。如果此计数小于2,则将match_id保留在结果集中。

WITH cte AS (
    SELECT match_id
    FROM public.perm_message_log
    GROUP BY match_id
    HAVING SUM(CASE WHEN reply_batch THEN 1 ELSE 0 END) < 2
)
SELECT t1.match_id,
       t1.from_id
FROM public.perm_message_log t1
INNER JOIN cte t2
    ON t1.match_id = t2.match_id
WHERE NOT t1.own_account

修改

如果您想使用CTE返回的match_id集来删除另一个表中的某些行,您可以尝试:

DELETE
FROM already_matched
WHERE match_id IN (SELECT t.match_id FROM cte t)