简体   繁体   中英

MySQL Share user_id with users table and admins table

I am creating a table for comments and one of the fields is user_id . Well both a regular user and an administrator will be able to post a comment so I'm not sure how I would do that.


Users table has a primary key of user_id

Admins table has a primary key of admin_id


So how would I do that?

why not have all of the users and administrators in one table and have a column "isAdmin" - if user is admin set to 1, default is 0

or

your comments table should have two columns and either user_id or admin_id updated, default 0 - but this is not a nice way...

If you can redesign to have a single table ( login ?) with an isAdmin flag, I'd do that.


If you can't, then have a process that causes every entry in the admin table to create a related entry in the user table. The admin table can then have a user_id field to relate the two together.

In this way every admin has a user, and all comments can be made using that user_id.


I would strongly avoid having comments keyed against both user_id and admin_id, with one of them being kept NULL. It will make queries untidy, obstruct you from enforcing constraints, and tie you to he messy two-key method if you encounter a similar need anywhere else.

You could accomplish this a couple of different ways. either have one commenter_id which links to either the user_id or the admin_id with an associated user_type flag or have two commenter_id fields, one for users and one for admins and key off of which field has a value to determine which table to go to for any related queries. I'm sure there are other much more elegant options but these two are the quick and dirty options.

Then you can make table -comments as

comment_id-int
user_id-fk from users table or admin table
user_type- enum('admin','user')
comment

//And other necessary fields

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