(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.
Related
Consider the following schema to student and several courses.
Student(Regno:integer, Sname:string, Degree:string, Age:integer)
Course(Coursecode:string, Cname:string, Credit:integer)
Enrolled(Regno:integer, Coursecode:string)
My problem is, SQL script to ensure that a student enrolls for maximum of 8 courses?
is there any possibility to use CONSTRAINTS for achieve this?
In theory you could enforce such a constraint in the database as follows:
Add an int field
Add a constraint so that this new int must be between 1 and 8 inclusive
Create a unique index on the new field + your student identifier
If you do the above, it is impossible to have more than 8 records per student.
That being said, a rule like is probably best enforced at the application level and not in the database.
It is possible to do with SQL Server, but you can't do it only with constraints. The easiest thing to do is to use a trigger for insert/update that will roll back if you attempt to enroll a student to too many courses.
Assuming the Enrolled table have a unique constraint on the combination of Regno and Coursecode (which it should - that should be it's primary key), you can use a trigger as simple as this:
CREATE TRIGGER EnsureMaxEnrolled
ON Enrolled
FOR INSERT, UPDATE
AS
IF EXISTS (
SELECT 1
FROM Enrolled As E
JOIN Inserted As I
ON E.Regno = I.Regno
GROUP BY E.Regno
HAVING COUNT(*) > 8
)
ROLLBACK TRANSACTION;
GO
However, I would probably think twice about using such a trigger - the requirement of a maximum number of courses per student is a business requirement, I don't think it's the database's job to enforce business rules.
I want to do some automatic updates between MySQL many tables, but I wonder how to do it fine. Here is an example :
Table `articles` : ID, TEXT, DATE, DELETED
Table `comments` : ID, TEXT, DATE, DELETED
Table `users` : ID, NAME, AGE, DELETED
Table `link` : ID, ARTICLE_ID, COMMENT_ID, USER_ID, DELETED
As you guess, the link table contains IDs from others.
I have already designed my database like this, to keep tables with the lowest columns as possible.
I know there are lots of questions here about it, but I don't really know what is the best solution. So here is what I want to do :
When a comment is deleted (update comments set DELETED=1 where ID=...), I want to update the column link.DELETED (=> 1).
When a user is deleted (update users set DELETED=1 where ID=...), I want to update the columns link.DELETED (=> 1) and articles.TEXT (=> NULL).
I know I can use foreign keys between link.ARTICLE_ID and article.ID for example, and simply delete rows. But I have put limited rights on the user used by my website. I will cron a batch with a more powerful user to delete rows tagged DELETED to cleanup the database.
Is it possible to do that wih FK, or should I use triggers (I don't really know how to use them) or something else ?
I have tried to put FK between DELETED columns but when I update a comments row, all link ones are updated too :/
Thanks for your help.
I've done what I wanted with the 2 solutions :
With a trigger : pseudo-delete (update DELETED=1 ...) causes pseudo-delete in my link table.
With a foreign key : true delete (delete from ...) causes true delete in my link table.
So, I can pseudo-delete rows from my website, with the basic user.
And I can clean my base with my batch using a user with delete rights.
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*.
I have an existing table of contacts that has about 140k records in it. I am introducing a parent table (let's call them "parent_contacts") such that one parent_contact can have many contacts; but initially, parent_contacts will be seeded to have one record for every contact that currently exists in the database.
I thought I was being clever in trying something like the following, which I now understand is not allowed (assume all the necessary parent_contact records have been created ahead of time):
UPDATE contacts
SET contacts.parent_id =
(SELECT parent_contacts.id FROM parent_contacts
WHERE NOT EXISTS
(SELECT * FROM contacts AS c WHERE c.parent_id = parent_contacts.id) LIMIT 1)
(If not readily apparent, the idea here being to set the parent_id of each contact to the id of the first parent_contact that another contact isn't already linked to)
Since this particular approach is not possible, is there another way of doing this that doesn't involve executing 140k individual update statements?
FOLLOW-UP: I resolved this by introducing a temporary child_id on the parent table, which I then removed after the seeding was finished. But in the context of the original question, I think Tony's answer below sounds apt.
You seem to have done this backwards
Add Parent_id to contacts (no constraint yet!)
Update Contacts filling Parent_id with a unique number.
Create ParentContracts, Don't put Identity in or Primary key.
The backfill ParentContacts with a Insert into ParentContacts Select Parent_id, .... From Contacts
Add the Identity (don't forget seed to next value) and Primary key to ParentContacts
Add the foreign key constraint to Contacts.
Nice easy steps and easy to check each one instead of this whole cloth manouvre you are trying now.
I have two related tables, quite common case: Clients(CID, name, surname) and Visits(VID, VCID, dateOfVisit) - VCID is the Client ID. How to manipulate foreign keys, when I want database to delete Visits records relative to some Client, who I DELETE, and to delete Client, when I DELETE the last Visit of that client left?
I would suggest you do a soft delete, so you can keep your Visits record.
Soft delete means you just add an extra field is_active default it to true, and when you delete the record flip it to false.
you can automatically delete visits for deleted clients by using "on delete cascade". something like:
create table clients (id integer primary key);
create table visits (id integer primary key,
client integer,
foreign key (client) references clients(id)
on delete cascade);
but going the other way (automatically deleting clients with no visits) is more difficult.
you can manually delete clients with no visits by executing:
delete from clients where id in
(select cid from
(select clients.id as cid, visits.id as vid
from clients left join visits on (clients.id = visits.client))
where vid is null);
(and maybe there's something simpler?). so either run that every now and then, or create a trigger that runs it when something is deleted from visits (although if you're going to add a trigger it could use the deletion info to do something smarter).
or maybe someone with more time/energy than me can write an answer with the trigger...?
(as others have said, automatically deleting clients is pretty drastic behaviour - it's not something you'd normally want to do in a production system - apart from anything else, if clients need more visits they are going to be pretty annoyed if they have to enter their details again...)