Database 1...n relation with several owner tables - mysql

I want to create a database scheme and don't really know a solution for the following scenario:
I have users, teams and projects. I want to enable to create projects as a user, but also as a team. What I thought of, was to include two foreign keys in the projects table. One for 'userId' and one for 'teamId'. But in this case for each entitiy either userId or teamId would be null.
Is this a good solution or is there a better possibility to solve that?

You can create a constraint that would force userId != null OR teamId != null.
Alternatively, you can require each project to have a non null foreign key userId (some user in the team had to actively create the project, right?), and then create an associatedTeam foreign key (which can be optional).

Related

Foreign keys in mysql

I have a doubt about the way of relating some tables. I have these tables:
User table: username (primary key)
Team table: team_name(primary key), username (foreign key references User(username))
With this relationship, I get that an user can have more than one team.
Group table: group_name (primary key)
I want that a group can have many teams, but these teams have to be of different users, so two teams of a user cannot be in the same group.
I have thought to do a relationship with the three tables of this way:
Group_teams table: (group_name, username, team_name). This table would have a composite primary key (group_name and username), in this way I would be sure that an user cannot has more than one team in a same group.
In addition, I think that I should create a composite foreign key references User(username) and Team (team_name) to be able to control that the team of a user exists. Finally, I should create another foreign key references Group (group_name) to control that a group exists.
I'm not sure that it would be of this way because I have errors when I try to do it. Could yo help me and tell me your opinions?
If a user can be on (at most) only one team, then you have a 0/1 - many relationship.
The easiest approach is to have TeamId in the Users table. This would be a foreign key reference to Teams.
There is no need for a third table to represent this relationship.
There's no need to reproduce the username field in the Group_teams table, just have group_name & team_name.
Create a trigger on the Group_teams table to fire before a new row is inserted, checking for more other teams with the same username.
Have a look at the question "How do you check constraints from another table when entering a row into a table?", specifically this answer from Jim V describing such a setup.

Foreign Key Issue ERD

Good day folks . I am building a relational database . I am at the ERD Stage and i am having a problem. The situation is a customer can either be representing themselves or a company and a company might have different customers because of different departments.
the problem is i need to link the customers and company table, as to run queries such as what organisation a customer works for, but not all customers rep a company therefore i am thinking i cannot put the com_ID attribute as a foreign key in the customer table or put the c_ID in the company table because there are instances where a customer doesnt represent a org therefore the foreign key would be null in some instances which i know cannot happen...Any suggestions would be great.
Thank you very much for your time
A foreign key can be null in MySQL and most DBMS. This is why you can create an ON UPDATE or ON DELETE SET NULL.
The best solution is primarily opinion, but using com_id allowing null values would seem to work fine. You can also set the default to null. This would also allow you to create customers before you create companies and then assign a customer to a company, depending on your software, creating a higher degree of flexibility.
For this I would also recommend the referential integrity of ON UPDATE CASCADE, ON DELETE SET NULL. This would allow you to keep a customer updated on the update of a company and the contact in your database should you delete a company*.

MySQL cascading tables

(My website is built using PHP and MySQL.)
My DB structure for users is mainly composed of 2 tables: "doctors" and "clients".
However, in order to integrate a chat system, I need to create a third table, namely 'chat_users', which combines both doctors and clients: fields of 'chat_users' table are
userid (unique integer),
username,
type (0:client, 1:doctor),
refid (id of the user in the associated clients or doctors table)
But I do not want to insert/delete/update this table manually each time a client or doctor is inserted/updated/deleted. I heard about cascading table some time ago...
What would be the best way performance-wise to do so? How can I achieve it?
I'm not sure you'll consider this an "answer", but may I comment on your database architecture?
You will be much happier in the long run having the following tables:
user_account: (ua_id, ua_email, ua_username, ua_password, etc.)
doctor: (d_id, ua_id, etc.)
customer: (c_id, ua_id, etc.)
In other words, have your relation going the other way. Then if you would like to be able to delete a doctor or customer by simply deleting the user_account, you can add the following relational constraint:
ALTER TABLE `doctor`
ADD CONSTRAINT `doctor_fk_user_account` FOREIGN KEY (`ua_id`) REFERENCES `user_account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `customer`
ADD CONSTRAINT `customer_fk_user_account` FOREIGN KEY (`ua_id`) REFERENCES `user_account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
What you need is an AFTER INSERT Trigger. This would allow you to create new users. In case if you want it to be updated on update and deleted on delete of the original record then you need those triggers as well.
CREATE TRIGGER `chat_users_insert` AFTER INSERT ON `doctors`
FOR EACH ROW BEGIN
INSERT INTO `chat_users` SET user_id= NEW.id;
END;
The above would insert a record and set the value of id. http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html can give you exact syntax. Let me know if you need any specific clarifications.
I know, this is not exactly an answer to your question but what about using an old fashioned view instead? This would save you from storing redundant data altogether.
CREATE VIEW chat_users AS
SELECT drid uid, drid userid, drname username, 0 FROM doctors
UNION ALL
SELECT clid+100000, clid, clname, 1 FROM clients
This view will have unique uids only if you don't have more than 100000 doctors in your table (otherwise choose a higher offset). The advantage of this approach would be that there is no dependent table data to maintain.
"I do not want to insert/delete/update this table manually each time a client or doctor is inserted/updated/deleted."
Why are you fretting about this? Just do it. You have application requirements that mandate it, so unless you can figure out how to unify your client and doctor tables, you will need a third that relates to your chat function.
The difficulty of adding this in an application framework is almost zero, it's just the case of creating an additional record when a client or doctor is created, and removing it when their respective record is deleted.
The other answers here propose using views or triggers to obscure what's really happening. This is generally a bad idea, it means your application isn't in charge of its own data, basically handing over control of certain application logic functions to the database itself.
The best solution is often the most obvious, as that leads to fewer surprises in the future.

mysql: proper way to handle relation between users and teams?

Newish to mysql DBs here. I have a table of USERS and a table of TEAMS. A user can be on more then one team. What's the best way to store the relationship between a user and what teams he's on?
Lets say there are hundreds of teams, each team consists of about 20 users, and on average a user could be on about 10 teams, also note that users can change teams from time to time.
I can think of possibly adding a column to my TEAMS table which holds a list of user ids, but then i'd have to add a column to my USERS table which holds a list of team ids. Although this might be a solution it seems messy for updating membership. It seems like there might be a smarter way to handle this information... Like another table perhaps? Thoughts?
Thanks!
ps, whats the best field type for storing a list, and whats the best way to delimit?
whats the best field type for storing a list, and whats the best way to delimit?
It's usually a really bad idea to try to store multiple values in a single column. It's hell to process and you'll never get proper referential integrity.
What you're really looking for is a join table. For example:
CREATE TABLE user_teams (
user_id INT NOT NULL FOREIGN KEY REFERENCES users(id),
team_id INT NOT NULL FOREIGN KEY REFERENCES teams(id),
PRIMARY KEY (user_id, team_id)
);
so there can be any number of team_ids for one user and any number of user_ids for one team. (But the primary key ensures there aren't duplicate mappings of the same user-and-team.)
Then to select team details for a user you could say something like:
SELECT teams.*
FROM user_teams
JOIN teams ON teams.id= user_teams.team_id
WHERE user_teams.user_id= (...some id...);

Best datastructure for this relationship

I have a question about database 'style'.
I need a method of storing user accounts. Some users "own" other user accounts (sub-accounts). However not all user accounts are owned, just some.
Is it best to represent this using a table structure like so...
TABLE accounts (
ID
ownerID -> ID
name
)
...even though there will be some NULL values in the ownerID column for accounts that do not have an owner.
Or would it be stylistically preferable to have two tables, like so.
TABLE accounts (
ID
name
)
TABLE ownedAccounts (
accountID -> accounts(ID)
ownerID -> accounts(ID)
)
Thanks for the advice.
I would keep the tables separate.
Self-referencing foreign keys can cause a lot of pain to update/delete.
With the combined table, a cascading delete on the owner will then delete all the owned accounts. (Which may or may not be desirable.) With the separate table, a cascade delete will only delete the relationship that the accounts were owned, and not the accounts themselves.
2nd choice is the best.
On a theoretical point of view, it is a regression of a 'n-to-m' (or 'many to many') relationship, where 'n' and 'm' side tables are merged in one unique 'Accounts' table, and where 'OwnedAccount' table is the linking table.
Using this model will allow you to implement data integrity rules at the server level without any problem. In addition to #mdma arguments, it will also make querying and reporting a lot easier. Further 'extensions' of ownership rules (multiple owners for one account, cascading ownership) could also be implemented in this model.