Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL选择字段包含值的电子邮件_Mysql_Sql_Conditional Statements - Fatal编程技术网

MySQL选择字段包含值的电子邮件

MySQL选择字段包含值的电子邮件,mysql,sql,conditional-statements,Mysql,Sql,Conditional Statements,我想做一个简单的选择,但条件对我来说有点棘手(因为我是SQL初学者) 我得到了这张桌子: userid | email | newsletters 1 | test@example.com | 1,2 2 | test2@example.com | 1 现在,我想得到所有的电子邮件地址的用户,希望得到通讯“2” 这将是: email | newsletters test@example.com | 1,2 当然,在另一个查询中,所有订阅1号新闻稿

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

我得到了这张桌子:

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%'
如果您想拥有更多,那么表规范化将非常有用

编辑: @评论中的SGEDES有一个很好的建议,可以为任何数量的时事通讯工作:

SELECT email FROM users WHERE concat(',',newsletters,',') LIKE '%,2,%'
如果您确实想这样做,请使用,但我认为您需要重新设计表结构。您不应该在用户表中存储每个用户的新闻稿,而应该在用户和报纸之间创建一个桥接表,如下所示:

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
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'
要获取想要镜像的用户的所有电子邮件地址,请编写以下内容:

select a.email
from   User a,
       UserNewspaper b
where  a.userid = b.userid
and    b.paperid = 2
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'

1.请参阅规范化您应该规范化
时事通讯
信息,这样您就不必进行这些黑客操作。。但是像“%”,2%或“2,%”之类的
应该可以实现purpose@amdixon-如果
时事通讯
只是
'2'
正确,您的建议将不起作用,您需要一组特殊条件,这只是开始请再次阅读我的答案:“假设您有此功能,则此功能将不正确地返回时事通讯中包含“2”的记录,例如“1,12,15”。@MichalKordas——也许更好的解决方案是
其中concat(',','时事通讯','),如“%,2,%”
,其中包含大于9的值。话虽如此,规范化是最好的方法。好吧,那么创建另一个名为subscriptions的表并设置行:id、userid、newsletteId而不是将其写入users表会很有用吗?