从排除的域列表中排除电子邮件地址

时间:2015-05-09 21:01:11

标签: postgresql database-design

我有一个电子邮件客户端,其中列出了您在Gmail收件箱中看到的电子邮件。

所有电子邮件都存储在Postgres 9.3.5数据库中。

我想要实现的部分功能是允许用户阻止来自域列表的传入电子邮件,例如@ spam.com,

我有this sqlfiddle,其中包含模式的简化版本,我有一个emails表和一个email_participants表。用户可以选择选择要排除的域名,例如他们可以选择从yahoo.com,hotmail.com等中排除电子邮件。

目前查询基本上是这样的:

SELECT subject, ep.email_id, kind, ep.user_id, ep.contact_id
FROM emails e
INNER JOIN
email_participants ep
ON ep.email_id = e.id
-- and ep.address domain doees not include *.yahoo.com, *.hotmail.com or whatever
WHERE kind = 'sent'
ORDER BY sent_at DESC;

我想将排除的域存储在表中,但我不知道如何从一组数据中使用类似的查询进行排除。

2 个答案:

答案 0 :(得分:4)

  

用户可以选择选择要排除的域名

这表明在后端你需要一个具有user_id&的表。 exclude_domain作为列:

CREATE TABLE user_excludedomain (
    user_id INTEGER NOT NULL,
    domain VARCHAR(255) NOT NULL,
    CONSTRAINT user_excludedomain_pkey PRIMARY KEY (user_id, domain),
    CONSTRAINT user_id_fkey FOREIGN KEY (user_id)
      REFERENCES users (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE);

然后在您的选择查询中,将left join添加到此表格&构造where clause以删除连接从此表中产生一行的行。 即

SELECT
    e.subject, 
    ep.email_id,
    e.kind,
    ep.user_id,
    ep.contact_id
FROM emails e
INNER JOIN email_participants ep 
    ON ep.email_id = e.id
-- left join all domains to be excluded
LEFT JOIN user_excludedomain uex 
    ON uex.user_id = ep.user_id 
    AND uex.domain = SUBSTRING(ea.address from '@.*') 
WHERE kind = 'sent'
  AND uex.user_id IS NULL -- pick only rows where the left join returns null (i.e. the excluded domain is not joined)
ORDER BY sent_at DESC;

答案 1 :(得分:1)

这可能不完全正确,但足够接近让你到那里......试试:

and substring(ea.address from '@.*') not in ('@yahoo.com', '@hotmail.com')

在上下文中:

SELECT subject, ep.email_id, kind, ep.user_id, ep.contact_id, ea.address
FROM emails e
INNER JOIN
email_participants ep
ON ep.email_id = e.id
JOIN email_addresses ea
ON ep.contact_id = ea.contact_id
and substring(ea.address from '@.*') not in ('@yahoo.com', '@hotmail.com')
WHERE kind = 'sent'
ORDER BY sent_at DESC;