简体   繁体   English

一类的通讯类别,例如1,2-Mysql Simple Database Design

[英]Newsletter Categories in one row like 1,2 - Mysql Simple Database Design

I'am using a simple newsletter-script where different categories for one user are possible. 我正在使用一个简单的新闻稿脚本,其中一个用户可以使用不同的类别。 But I want to get the different categories in one row like 1,2,3 但我想像1,2,3这样一排地得到不同的类别

The tables: 表格:

newsletter_emails newsletter_emails

id  email          category
1   test@test.com    1
2   test@test.com    2

newsletter_categories newsletter_categories

id  name
1   firstcategory
2   secondcategory

But what Iam looking for is like this: 但是Iam寻找的是这样的:

newsletter_emails newsletter_emails

user_id  email                category
1        test@test.com        1,2
2        person@person.com    1

what's the best solution for this? 最好的解决方案是什么?

PS: The User can select his own Categorys at the profile page. PS:用户可以在个人资料页面上选择自己的类别。 (maybe with Mysql Update?) (也许使用Mysql Update?)

SQL and the relational data model aren't exactly made for this kind of thing. SQL和关系数据模型并不是专门针对这种情况而制作的。 You can do either of the following: 您可以执行以下任一操作:

  • use a simple SELECT query on the first table, then in your consuming code, iterate over the result, fetching the corresponding rows from the second table and combining them into a string (how you'd do this exactly depends on the language you're using) 在第一个表上使用简单的SELECT查询,然后在使用的代码中遍历结果,从第二个表中获取相应的行,并将它们组合成字符串(您的操作方式完全取决于您使用的语言使用)

  • use a JOIN on both tables, iterate over the result set and accumulate values from table 2 as long as the ID from table 1 remains the same. 在两个表上都使用JOIN ,迭代结果集并累积表2中的值,只要表1中的ID保持不变即可。 This is harder to code than the first solution, and the result set you're pulling from the DB is larger, but you'll get away with just one query. 这比第一种解决方案更难编码,并且从数据库中提取的结果集更大,但是您只需一个查询就可以摆脱困境。

  • use DBMS-specific extensions to the SQL standard (eg GROUP_CONCAT ) to achieve this. 使用特定于DBMS的SQL标准扩展(例如GROUP_CONCAT )来实现此目的。 You'll get exactly what you asked for, but your SQL queries won't be as portable. 您将获得所需的确切信息,但是您的SQL查询将不会那么容易移植。

试试这个(完全未经测试):

SELECT id AS user_id, email, GROUP_CONCAT(category) AS category FROM newsletter_emails GROUP BY email ORDER BY user_id ASC;

This is a many-to-many relationship case. 这是一个多对多关系的案例。 Instead of having comma separated category ids make an associative table between newsletter_emails and newsletter_categories like user_category having the following schema: 而不是用逗号分隔类别ID,而是在newsletter_emails和newsletter_categories(例如user_category)之间建立具有以下模式的关联表:

user_id    category
1          1
1          2
2          1

This way you won't have to do string processing if a user unsubscribes from a category. 这样,如果用户取消订阅类别,则无需进行字符串处理。 You will just have to remove the row from the user_category table. 您只需要从user_category表中删除该行。

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

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