简体   繁体   English

MySQL SELECT电子邮件,其中字段包含值

[英]MySQL SELECT email where field contains a value

I would like to do a simple select - but the condition is a bit tricky for me (because I'm a SQL-beginner). 我想做一个简单的选择-但条件对我来说有点棘手(因为我是SQL入门者)。

I got this table: 我得到这张桌子:

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

Now I would like to get all email-addresses of users, which want to get newsletter "2". 现在,我想获取用户的所有电子邮件地址,并希望获取时事通讯“ 2”。

This would be: 这将是:

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

And of course: In another query all users, which are subscribing newsletter number 1: 当然:在另一个查询中,所有用户正在订阅新闻通讯1:

Result: 结果:

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

What would be the correct sql-query? 什么是正确的sql查询? I think this should be the right beginning, but I don't know which condition I have to use: 我认为这应该是正确的开始,但是我不知道我必须使用哪种条件:

SELECT email FROM users WHERE newsletter CONDITION?

Could you please help me out? 你能帮我吗? :-) :-)

This will do the work assuming number of newsletter can't be higher than 9 : 假设时事通讯的数量不能超过9这将完成工作:

SELECT email FROM users WHERE newsletters LIKE '%2%'

If you'd like to have more of them then table normalization would be very helpful. 如果您想拥有更多它们,那么表规范化将非常有帮助。

EDIT: @sgeddes in comments has great proposition to make it working for any number of newsletters: 编辑: @sgeddes在评论中有很好的主张,使其可用于任何数量的新闻通讯:

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

Use a regular expression if you really want to do this, but I think you need to redesign your table structure. 如果您确实想这样做,请使用正则表达式 ,但是我认为您需要重新设计表结构。 Instead of storing the newsletters per user in the User table, you should create a bridge table between User and Newspaper like this: 与其在User表中存储每个用户的新闻通讯,不如在User和Newspaper之间创建一个桥接表,如下所示:

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)

To get all email-addresses of users that want paperid 2 you'd write this: 要获取需要paperid 2的用户的所有电子邮件地址,请编写以下代码:

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

To get all email-addresses of users that want the Mirror you'd write this: 要获取需要镜像的用户的所有电子邮件地址,您可以这样编写:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM