How do delete related data in MySQL tables in a database? - mysql

I'm sure that this is a very basic question but, I at a loss and recently starting with MySQL. I have modified, created databases, users, tables, added and modified entries to the table but now I think I need to use a Join here, but I'm not sure.
In the same db I have two tables. The tasks table has two columns of interest user and keyid. While the activities table has one column of interest which is task. What I need to do is delete all tasks in the table tasks for a certain user. However, this also means I need to delete all activities for those tasks. Now the way these are related, is that the keyid value in the tasks table is the value in the task column in the activities table.
My question is how do I write the DROP or DROP + JOIN query to do this?

You could use JOIN on this one like:
DELETE Tasks, Activities
FROM Tasks INNER JOIN Activities
ON Tasks.KeyID = Activities.Task
WHERE Tasks.User = 'User Name Here'
But it would have been better if you use ON DELETE CASCADE when you designed the table so that you will have to delete from the mother table and all the related records of the child table would also be deleted automatically.
See example here.

You could do it in 2 separate queries?
DELETE FROM activities WHERE task IN
( SELECT keyid FROM tasks WHERE user = 'CertainUser') ;
DELETE FROM tasks WHERE user = 'CertainUser' ;

Related

MySQL delete row from at least one table using one query

I have two tables: one contains user logins and the other contains user data. I would like to delete users who may or may not exist in the latter table but definitely exist in the former. How do I account for users who may or may not exist? Please note that it should be in one query....I have tried:
DELETE houses,houseusers FROM houses INNER JOIN houseusers ON houseusers.username = houses.username WHERE houses.username='user1' OR houseusers.username='user1';
START TRANSACTION;
DELETE FROM houses WHERE username='user1';
DELETE FROM houseusers WHERE username='user1';
COMMIT;

How to efficiently delete from table A that is joined with table B and table A has an after delete trigger?

I have a products table, a category table and a join-table to link the two, named prod_cat_join. I am attempting to periodically delete all categories not associated with a product with a specific team ID. Let it be known that category has a trigger that deletes all joins in prod_cat_join associated with a category after a category is deleted. Is there a single SQL query that can be invoked to delete all categories not associated with a product and is associated with a specific team ID without running into a function/trigger error?
The trigger goes as follows:
CREATE DEFINER=`dbe1`#`%` TRIGGER `db`.`category_AFTER_DELETE` AFTER DELETE ON `category` FOR EACH ROW
BEGIN
delete from prod_cat_join where prod_cat_join.categoryID = ID;
END
And my query that is periodically called to delete all categories not associated with a product is:
DELETE db.category FROM db.category
LEFT JOIN db.prod_cat_join AS join_cat
ON join_cat.categoryID = db.category.ID
WHERE join_cat.productID IS NULL AND db.category.teamID = '1234'
I know it's possible to query all categories not associated with a product then delete the returned set of unassociated categories. But that seems inefficient as it requires two queries. Given our current setup is it possible to bypass the trigger to run the aforementioned query? Or is there some other single query method to delete the unassociated categories? And would putting an after delete trigger in prod_cat_join to delete all categories who no longer have an association to a join be effective? Would that not end up invoking the above-mentioned deletion trigger?
Guidance would be appreciated, thank you.

How to make one column mirror another in mysql

I have two tables one called users and another called profiles. Each of these tables has a column named user_id. What I want to do is when I insert a new user into the users table, I want to automatically copy over their new user_id in the users table to the profiles table. I don't want to use the UPDATE clause because then I would have to call that every time I add a new user. I thought that relations would achieve what I am trying to do so I made the user_id from profiles reference the user_id from users and it still doesn't update automatically. What should I do? And what is the point of relations in the first place if they don't update your columns automatically?
This is probably a design error. If rows in these two tables always exist with the same IDs, they should probably be a single table.
The foreign key you've created only guarantees that every row that exists in profiles must have the same ID as a row in users. It does not cause those rows to be created -- it just means that if you try to create a row with an ID that doesn't match, the database will throw an error.
That all being said, it's possible to create a trigger to do what you're describing:
CREATE TRIGGER user_insert_creates_profile
AFTER INSERT ON users
FOR EACH ROW
INSERT INTO profile (user_id) VALUES (NEW.user_id);
But it's probably better to reconsider your design, or to do the insert in your application. Triggers are best avoided.

How to fetch data using One to Many relationship using MySql and joins in MySql

I am creating a demo application. I am stuck in a scenario, I am not getting the exact way and query to fetch data from sql database in the following scenario:
I have a table named RegistrationTable, this table has a column RegistrationId as its primary key. There is another table named ApplicationDetails, this table has a column ApplicationId as its primary key.
I have referenced ApplicationId as Foreign key to RegistrationId column.
My requirement is, single user can apply to multiple jobs. job details will be present in ApplicationDetails table.
How can I check to how may jobs the user has applied based on his email id stored in registration table.
I have a column Status in ApplicationDetails table, where as soon as user applied to a job I am updating the status column.
I am trying the following query but its not working:
SELECT Status FROM ApplicationDetails
INNER JOIN RegistrationTable ON ApplicationTable.ApplicationId = RegistrationTable.RegistrationId
WHERE RegistrationTable.EmailId = "abc#xyz.com";
Can any one please suggest me how can I go about this. I am a beginner to SQL. Please do suggest a way to solve this. Thanks in advance.
You need to change the table name in your query to ApplicationDetails. This is what you mentioned in your post
SELECT Status FROM ApplicationDetails
JOIN RegistrationTable ON ApplicationDetails.ApplicationId = RegistrationTable.RegistrationId
WHERE RegistrationTable.EmailId = "abc#xyz.com";

MySQL update table 1 with table 2 data

Sorry for the ambiguous title.
I have two tables:
table 1: mailing_email
table 2 (dynamic table but for now is): membership
table 1 contains a list of all email accounts in the database and few ancillary fields such as name. It also has a column called communicate.
communicate is basically my terminology for subscribed. Any unsubscribe link will set communicate to false.
Both mailing_email and membership have a email and communicate column.
I need to write a query where the following happens:
mailing_email.communicate gets updated to the current status of membership.communicate where mailing_email.email = membership.email. If an email exists in mailing_email which does not exist in membership, the communicate field stays the same.
How would i go about doing this the fastest possible way? Each table will have thousands of rows this sync command would run often.
MySQL offers an update join syntax:
UPDATE mailing_email
JOIN membership ON mailing_email.email = membership.email
SET mailing_email.communicate = membership.communicate