简体   繁体   English

使用来自另一个表的concat更新MYSQL中的值

[英]Update values in MYSQL with concat from another table

I've been trying to update values of a field from another table's field with comma separators. 我一直在尝试使用逗号分隔符从另一个表的字段中更新字段的值。

This is my current code: 这是我当前的代码:

update programs set registered = (select user_id from users where reg_prog != 0)

I am getting #1242 mysql error. 我收到#1242 mysql错误。

I would like to have a list like this: Registered users: 47, 97, 10, 618, 5 (these are the ids of the users that are registered to the program). 我想要一个这样的列表:注册用户:47、97、10、618、5(这些是注册到该程序的用户的ID)。

Any help? 有什么帮助吗?

Don't do it like this. 不要这样 Use a normalized data model . 使用规范化的数据模型 Having any kind of comma-separated list in a database field usually is a very bad idea. 在数据库字段中使用任何以逗号分隔的列表通常是一个非常糟糕的主意。 You have no way of properly working with these values, because you always need messy string manipulation to do anything with this. 您无法正确使用这些值,因为您始终需要进行混乱的字符串操作才能对此进行任何操作。

If you need to record the users that registered to a program, create separate tables for users, programs and a relation table for both of them: 如果需要记录已注册程序的用户,请分别为用户,程序和两者创建关系表

 _________          ______________          _________
| program |        | user2program |        | program |
+---------+        +------------  +        +---------+
| id      |  <-->  | user_id      |        | name    |
| name    |        | program_id   |  <-->  | id      |
 ---------          --------------          ---------

It takes a little more programming effort, to keep these tables filled properly, but you will see that it works much better this way. 要使这些表正确填充,需要花费更多的编程精力,但是您会发现这种方法会更好。

There is no single SQL statement that can do what you are looking for in your question. 没有单个SQL语句可以完成您在问题中寻找的内容。 If you have a proper data model, you need to first insert your program, then your user and afterwards add the releation between the two: 如果您有适当的数据模型,则需要首先插入程序,然后您的用户,然后在两者之间添加关系

INSERT INTO program (id, name) VALUES (1, "My Program");
INSERT INTO user (id, name) VALUES (1, "John Doe");
INSERT INTO user2program (user_id, program_id) VALUES (1, 1);

To get all users that are registered for a program , you can then use a SELECT statement with JOINs: 要获得已为某个程序注册的所有用户,可以将SELECT语句与JOIN一起使用:

SELECT p.name AS program_name, u.name AS user_name
FROM   program AS p
JOIN   user2program AS u2p ON p.id = u2p.program_id
JOIN   user AS u ON u.id = u2p.user_id
WHERE  p.id = 1 -- ID of the program

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

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