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

标签 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;

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

最佳答案

The user can choose to select as many domains they want to exclude

这表明在后端您需要一个以 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);

然后在您的选择查询中,向该表添加一个左联接 并构造where 子句 以从该表中删除联接产生一行的行。 即

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;

关于postgresql - 从排除域列表中排除电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30144974/

相关文章:

database-design - 哪些标签架构最有效/有效?

database-design - Redis 中的数据建模实践?

sql - 加快检查 CIDR 范围内的 IP 地址成员资格,适用于大型数据集

node.js - Knex 与 Heroku Postgres 连接时出错?

postgresql - Postgres : Convert TEXT to string or difference between 'abc' vs. 'a' || 'bc'

postgresql - 在 Postgresql 中向用户授予权限从不授予权限

php - 多用户平台收据序列号

大型表的 MySQL 主键列类型

database - 在数据库中使用继承的优点和缺点是什么

sql - 如何动态查询列名?