MySQL SELECT 字段包含值的电子邮件

MySQL SELECT email where field contains a value

我想做一个简单的 select - 但条件对我来说有点棘手(因为我是 SQL-初学者)。

我知道了 table:

userid | email             | newsletters
     1 | test@example.com  | 1,2
     2 | test2@example.com | 1

现在我想获取用户的所有电子邮件地址,这些用户想要获取时事通讯“2”。

这将是:

email | newsletters
test@example.com | 1,2

当然还有:在另一个查询中,所有订阅时事通讯编号 1 的用户:

结果:

email | newsletters
test@example.com | 1,2
test2@example.com | 1

正确的 sql 查询是什么? 我认为这应该是正确的开始,但我不知道我必须使用哪个条件:

SELECT email FROM users WHERE newsletter CONDITION?

你能帮帮我吗? :-)

假设时事通讯的数量不能高于 9:

,这将完成工作
SELECT email FROM users WHERE newsletters LIKE '%2%'

如果您想要更多,那么 table 规范化会很有帮助。

编辑: 评论中的@sgeddes 提出了让它适用于任意数量的时事通讯的好建议:

SELECT email FROM users WHERE concat(',',newsletters,',') LIKE '%,2,%'

如果您真的想这样做,请使用 regular expression,但我认为您需要重新设计 table 结构。与其将每个用户的新闻通讯存储在用户 table 中,不如在用户和报纸之间创建一个桥梁 table,如下所示:

User table
userid | email            
     1 | test@example.com 
     2 | test2@example.com

Newspaper table
paperid | name
      1 | the Sun
      2 | the Mirror

UserNewspaper Bridge table
userid | paperid     (represents, not part of table)
     1 | 1           (test@example.com receives the Sun)
     1 | 2           (test@example.com receives the Mirror)
     2 | 1           (test2@example.com receives the Sun)

要获取所有需要 paperid 2 的用户的电子邮件地址,您可以这样写:

select a.email
from   User a,
       UserNewspaper b
where  a.userid = b.userid
and    b.paperid = 2

要获取所有需要 Mirror 的用户的电子邮件地址,您可以这样写:

select a.email
from   User a,
       UserNewspaper b,
       Newspaper c
where  a.userid = b.userid
and    b.paperid = c.paperid
and    c.name = 'the Mirror'