简体   繁体   中英

MySQL: For every user, add a row to another table with that user's ID

I have a bunch of users in a project in the users table. I have a second table I use for notifications . When a user gets a notification for him, its added to the notifications table with his user_id and a read (true/false) flag.

Now, if I want to add a notification for every user (such as site going offline, etc), how would I add a row for every user in the users table? The new rows would be exactly identical with the exception of the auto_incremented row id but each new row would have to specify the user id.

Of course I could write a script in php to generate a ton of sql queries to do this and send them all at once using a multi-query insertion, but that seems computationally expensive if I have thousands of users.

Conceptual query: FOR users.id as user_id

INSERT INTO notifications VALUES (,user_id=user_id,msg='We will be going offline at 5:00!',read='0')

Is that do able?

Thanks!

If you have thousands of users, it doesn't matter to generate thousands of SQL querys, and send it to your MySQL server.

But things will change if you have millions of users.

One affordable choice is, write a notification to a table, for example, system_notifications . Display not only notifications but also system_notifications on your webpage.

And then save the ids for the users who have already read these notifications.

eg

system_notifications table
| id | message |

system_notifications_read_users table
| id | user_id |

Then, you can only operate your database when the user read the notifications.

And when your system notification expired, such as you have finished your downtime, you can remove it from both of tables said before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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