I'm trying to add foreign keys to a testing database seeded with a bunch of dummy data. I could go outside MySQL, export a list of missing IDs, and generate a bunch of insert statements in Python but I'm wondering if there is a way to handle this in MySQL
ALTER TABLE `kalos`.`award`
CHANGE COLUMN `awardee_user_id` `awardee_user_id` INT(11) NULL ;
ALTER TABLE `kalos`.`award`
ADD CONSTRAINT `fk_award_3`
FOREIGN KEY (`awardee_user_id`)
REFERENCES `kalos`.`user` (`user_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE;
I've tried messing with the ON DELETE and ON UPDATE properties but it definitely won't let me apply it because there are user ID's in the award table that are not present in the user table (only about 200 out of 3000). Like I said it would be fairly simple to do this in Python but I've run into this issue a few times and am really curious to see if MySQL can handle something like this on it's own.
I figured this out and it was extremely simple.
DELETE FROM t1
WHERE
t1.id NOT IN (SELECT
id
FROM
(SELECT
tmp.id AS id
FROM
t1
INNER JOIN t2 ON t1.id = t2.id) as tmp)
This will delete any row from t1 that does not have a corresponding record in t2
Related
table 1 is called (athlete) and table2 is called (training_session.id) the primary key to table 1 is ID, and the table 2 has the primary key Athelete_id
I want to delete a person from my database by using his name, which I've called "Pet". However, he is also connected to another table which stores his training session. So (ID 1) on table 1 is connected to table 2 (athlete id1)
I struggle a lot, I try using INNER JOIN.
DELETE athlete,training_session FROM athlete
INNER JOIN
training_session ON training_session.id = athlete.name
WHERE
athlete.name = "Pet;
I have something wrong with my syntax, is it correct to use Inner Join or have I misunderstood
You should have set up foreign key constraints with Cascade deletions to simplify the logic and all you would have needed than was to delete from athlete. So I would suggest you add it.
For more info you can take a look at:
http://www.mysqltutorial.org/mysql-on-delete-cascade/
For this error message, is there a way for mysqlimport to output the specific row that fails the constraint? It's good for debugging. Otherwise, I don't know which row has this problem.
mysqlimport: Error: 1452, Cannot add or update a child row: a foreign key constraint fails (`bwordDS`.`Category_Term`, CONSTRAINT `FK_qn1crq26sr0hqm5q2p7nfvdu1` FOREIGN KEY (`categories_id`) REFERENCES `Category` (`id`)), when using table: Category_Term
First check if Category table exist where you are trying to import this data.
if Category table exists then need to check that all category_id in this table should exist in Category table as id.
Better option is to import first category table and then this table.
In generic first all parent tables data should import then child tables.
A dirty way is as per below which is not recommended-
set foreign_key_checks=0;
import data here;
set foreign_key_checks=1;
Just to know which row is creating problem-
Below query will provide you problematic rows.
SELECT a.category_id FROM Category_Term a
LEFT JOIN Category b ON a.category_id=b.id
WHERE b.id IS NULL;
Note: Assuming category_id in category_term and id in category tables will be indexed.
I used the sample query provided by #Zafar, but I added DISTINCT to SELECT as well:
SELECT DISTINCT countries.city_id
FROM countries
LEFT JOIN cities ON countries.city_id=city.id
WHERE city.id IS NULL;
I want to delete specific rows from 8 tables.
My problem is that the rows are connected with foreign key.
How can I delete all the data that connected to the specific rows that I want to delete?
My tables include definition tables (like id, name ,max value, min value...),
data tables (like id, user_id, definition_id,....) and history tables (save every change in data table).
I thought to use delete on cascade command but I could not find a way to use it.
DELETE CASCADE is an attribute of the foreign key constraint. Unfortunately it's not something you can use as an option with a DELETE statement (which would be really cool actually)
If your foreign keys have not been declared as cascading you need to "work your way up".
Unfortunately you did not show us your real table structure so let's assume something like this:
main_table (main_id)
child_one (id, main_id)
child_two (id, id_one)
child_three (id, id_two)
(I know you said 8 tables, but for the sake of the demonstration I shortened it a bit, but that doesn't change the underlying "strategy")
Assuming you want to delete the row with main_id = 42 from `main_table:
You first need to delete the rows from child_three using something like this:
delete from child_three
where id_two in (select id
from child_two
where id_one in (select id
from child_one
where main_id = 42);
Then delete the rows from child_two:
delete from child_two
where id_one in (select id
from child_one
where main_id = 42);
Then child_one:
delete from child_one
where main_id = 42;
And finally the main table:
delete from main_table
where id = 42;
Some SQL clients can actually generate those statements for you. I don't know if SQL Developer can though.
I assume that you use InnoDB Engine, since you are talking about foreign keys,
Easier will be to define properly the table so that a deletion will act as a cascade deletion.
CONSTRAINT `myForeignKey` FOREIGN KEY (`typeId`)
REFERENCES `types` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
Here is alink with a proper create table statement:
How do I use on delete cascade in mysql?
Is there some nice automated way/program for cleaning up my database? I have a couple of tables with relations that in some cases just point at records that doesn't exist.
Sounds like you are missing some Foreign Key Constraints.
Depending on the ON DELETE option, orphaned records will be deleted together with the referenced records, referencing columns set to NULL, or deleting will be rejected.
You will have to delete those existing entries manually using a query like this, before creating your constraints:
DELETE FROM table_a
WHERE ref_b IS NOT NULL
AND NOT EXISTS ( SELECT 1 FROM table_b WHERE table_b.id = table_a.ref_b )
I have a table structured as follows:
table(A, B)
They are both primary keys and they are needed to connect two entries in another table (i.e. they simbolize a friendship between users).
I need to check the table and, if (A,B) exists, delete an eventual (B,A) (or vice-versa).
Since the database is huge, I can't do this manually for every single entry each time.
Of course, I programmed the script that populated the database to check for this situation and avoid it, but we've been using that script on 8 different PCs and so the different dumps may have "reverse duplicates".
The problem has arisen because the relationship you are trying to describe is symmetrical - but the schema models an asymmetric association. The right to model the problem would be to maintain a table of relationships - then have a table linking users to relationships, e.g.
relationship:
id auto_increment
related:
r_id foreign key references relationship.id
u_id foreign key references user.id
primary key (r_id, u_id)
But to clean up the existing data...an obvious approach would be...
DELETE FROM yourtable d
WHERE A>B AND EXISTS (
SELECT 1
FROM yourtable r
WHERE r.A=d.B
AND r.B =d.A
)
However, if I recall correctly MySQL doesn't like using a subselect in a delete which references the same table as the delete. So....
SELECT d.A,d.B
INTO dups
FROM yourtable d, yourtable r
WHERE d.A>d.B
AND r.A=d.B
AND r.B =d.A;
then....
DELETE FROM yourtable
WHERE EXISTS (
SELECT 1 FROM dups
WHERE dups.A=yourtable.A
AND dups.B=yourtable.B
)
Not sure if the pushed predicate will still cause a problem, so if that doesn't work....
DELETE FROM yourtable
WHERE CONCAT(A, '/', B) IN (
SELECT CONCAT(A, '/' B) FROM dups
)