I was wondering if this kind of thing will work:
Let's say I have two tables: COMPANIES and ADDRESSES. Each company can have only one address. Simplified schema would look like this.
COMPANIES
id
address_id
name
(...)
ADDRESSES
id
first_name
street
(...)
Now, I want to add foreign key on COMPANIES.address_id -> ADDRESSES.id ON DELETE SET NULL ON UPDATE CASCADE.
But I also want the address to be deleted when the company is deleted. So the other way around it would be ADDRESSES.id -> COMPANIES.address_id ON DELETE CASCADE. Is this safe and possible?
Maybe, instead of foreign keys, using triggers could be a solution to your problem.
create trigger addr_delete
after delete on companies for each row
begin
delete from addresses where id=old.address_id
end
Related
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 two tables. One called peoples another called addresses. The peoples table has a foreign constraint on the address table (peoples.address_id = addresses.address_id) Multiple people may have the same address. There is a unique constraint on the address column on the addresses table
I came across a situation where I have to delete a person from the peoples table and the associated address on the on the addresses table IF AND ONLY IF there is no other record in the peoples table who have the same address.
How can I go about doing this in MySQL?
This should be more performant than doing a subquery:
DELETE
addresses
FROM
addresses
LEFT JOIN peoples
ON addresses.address_id = peoples.address_id
WHERE
peoples.address_id IS NULL
It should delete all addresses that aren't referenced in the peoples table. If you want to only delete the specific address in question, add something to the WHERE clause like AND addresses.address_id = '<address_id>'.
Example
You can use a NOT EXISTS clause like below
DELETE FROM addresses
WHERE NOT EXISTS
(SELECT * FROM peoples WHERE peoples.address_id=addresses.address_id)
The cons against this is it will be pretty slow as it will re-run the query for every address row that exists. Otherwise it should solve the problem.
Delete the person first. Then this query deletes if the address has no people
(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.
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...)