Drew
Drew

Reputation: 6872

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?

Upvotes: 1

Views: 1812

Answers (4)

MatBailie
MatBailie

Reputation: 86765

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.

Upvotes: 2

Somnath Muluk
Somnath Muluk

Reputation: 57766

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

Upvotes: 0

Elen
Elen

Reputation: 2343

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...

Upvotes: 2

Brian
Brian

Reputation: 2229

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.

Upvotes: 0

Related Questions