Mysql foreign key and delete record - mysql

I have created two tables and they have a simple fk relationship. The tables are like below:
table_1
field_1 (primary key)
table_3
field_1 (fk on table_1)
field_2 (fk on table_2)
and then I have created the FK with the line below:
ALTER TABLE `table_2`
ADD CONSTRAINT `fk_table_2`
FOREIGN KEY (field_1`) REFERENCES `table_1` (`field_1`);
What I expect is that, if I try to delete a record in my table_1 where field_1 = x and another record with the same x value is present in table_2 as field_1, I should get an error.
Actually, I don't get any error and the record is removed from table_1 leaving an orphan child record in table_2.
I don't use the delete cascade because I want avoid this.
Why I don't get any error?

Related

Implement Foreign Key in mysql table

Im trying to restore some old database tables, that when i build them i did not user foreign keys. I have the field that corresponds to the Foreign Key, but i've not set it up in the relations table to which table it connected.
Right know i have a problem because if i try to add that relation, it cannot, because there are some rows deleted in the other table.
Is there any mysql command for checking this type NULL relations for me to delete the rows that i dont need.. and in the end.. add the relation.
TableA
id,
name
TableB
id,
tableA_id,
points
I've deleted some TableA rows.. now i cannot had that relation.
Any mysql command to help, or need to check manually?
Thanks
Assuming that you have PRIMARY KEY constraint at least on TableA.id you can try
-- Delete all orphaned records from TableB
DELETE b
FROM tableb b LEFT JOIN tablea a
ON b.a_id = a.id
WHERE a.id IS NULL;
-- Create a FK constraint
ALTER TABLE TableB
ADD CONSTRAINT fk_a_id FOREIGN KEY (a_id) REFERENCES tablea(id);
Here is SQLFiddle demo

INSERT with UPDATE on duplicate key

I have a query which updates the table or inserts if the row does not already exist, but for some reason it just inserts all the time.
This is my table structure:
Id (primary) | uid | product_id | quantity
This is my query:
INSERT INTO my_table (uid,product_id,quantity)
SELECT t1.uid,?,?
FROM checker t1
WHERE t1.id = ?
ON DUPLICATE KEY UPDATE
product_id = ?, quantity = quantity+?
What i want to do though is use on duplicate key if uid + product_id combination exist in the table already.
So is there a way to designate what kind of duplication to look for to update instead of insert?
There is no way to distinguish between what duplication occurs.
As soon as any unique constraint is violated - it will perform ON DUPLICATE KEY UPDATE part.
For your case you just need to create unique composite key that consists of 2 fields: (uid, product_id)

How to make a relation between two tables without foreign key

I'm a total newbie and I'm trying to do a mysql database, using xampp for linux 1.8.1.
I want to make a relation between two tables A and B. For what I know foreign keys create a bijection, or a one-to-one relation. I must not have such a strict relation, so I only created a column inside table A that stores the id of table B.
Is this correct? There's not a way to enforce it? I mean, this way you could delete a row of table B that is referenced in table A. you could store a value inside A that doesn't correspond to an id of any row of B. How to prevent this?
The main problem for me is to prevent deletion of a row of table B if the row id is referenced by a row of table A.
create table table_b (
b_id integer primary key
);
create table table_a (
b_id integer primary key references table_b (b_id)
);
insert into table_b values (1);
insert into table_a values (1);
The following statement will fail.
delete from table_b where b_id = 1;
If you'd built that with PostgreSQL, the error message would say
ERROR: update or delete on table "table_b" violates foreign key constraint "table_a_b_id_fkey" on table "table_a" Detail: Key (b_id)=(1) is still referenced from table "table_a".
That structure gives you a "1 to 0 or 1" relationship between the two tables. For "1 to 0 or many", add one or more columns to table_a's primary key.
create table table_b (
b_id integer primary key
);
create table table_a (
b_id integer references table_b (b_id),
checkout_date date not null default current_date,
primary key (b_id, checkout_date)
);
That structure will let table_a store multiple rows for one value of b_id, but each of those rows must have a different checkout_date.
I think you allways need an primarykey for this, or you write a trigger who checks the consistence of ID from B when a change occurs.
I dont know that it would be possible without a trigger or a constraint ...

how to update a primary key if it is also the foreign key to another table?

I have a table, tableA, which has a column myID. myID is a primary key in tableA and foreign key to tableB.
when i tried to update a particular record's myID in tableA:
update tableA
set myID = 123456
where myID= 999999
i got this error:
The UPDATE statement conflicted with the FOREIGN KEY constraint
"tableA_FK00". The conflict occurred in database "mydatabase" , table
"tableA" , column 'myID'.
i had set myID's Update Rule to 'Cascade' and Enforce Foreign Key Constraint to 'No' but i still cannot update. how should i proceed?
If there's a record in tableB that references tableA with PK 123456 and tableB is the table with the "tableA_FK00" constraint then you are violating the constraint. If you must change the PK of a row in tableA (and I'm not sure why you're doing that, PK's should never change!!!) you have the burden of making sure no other records reference it with FK constraints.
So if you insist on changing the PK in tableA:
Find which table has the constraint "tableA_FK00" (ensure it's only tableB see post here).
Temporarily remove the constraint in tableB
Update tableA
Update all rows in TableB that need their FK changed
Reapply FK constraint on tableB
Another option:
Insert all ids of rows from tableB with FK 123456 into a temp table (this table just has the keys of PK's from tableB)
Set tableB FK field to allows nulls
Set all fields in tableB FK = null by joining with the temp table on tableB PK
Change the row in tableA
Set all the rows in tableB to 999999 by joining with the temp table.
Try these steps:
Disable FK constraints temporarily (ALTER TABLE tableA WITH NOCHECK
CONSTRAINT ALL).
Update your Primary Keys
Update your Foreign Keys to match the Primary Keys change
Enable back enforcing FK constraints

Mysql database - primary key problem

I have 2 tables: let say table 1 (userid, username, password) and table 2 (userid, a, b, c).
table 1 has a userid field (primary key), table 2 also has userid (references table 1).
If I do an insert statement, to add a row to table 2, how does table 2 generate the userid field?
Edit:
I want to insert things into table 2 where the userid in table 2 MUST match userid in table 1 - what constraints do I need to set up
The database doesn't understand the relationship between table1 and table2 unless you explicitly specify it. You can use SQL foreign keys if you are using a database engine the supports them (InnoDB).
CREATE TABLE table1 (
userid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL);
CREATE TABLE table2 (
rowid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
userid INTEGER NOT NULL
REFERENCES table1(userid)
ON DELETE CASCADE ON UPDATE CASCADE
-- other columns here
);
The REFERENCES option will tell the database engine that table2.userid requires that a row exist in table1 such that table1.userid = table2.userid. The ON DELETE and ON UPDATE clauses will cause the deletion of a row in table1 to automatically delete/update rows in table2.
You cannot create a row in table2 until you have created a row for the user in table1. The row in table1 will auto-generate the userid. When you insert into table2, you will explicitly include the user id from table1 to establish the linkage between the rows.
If the userid field on table2 is not autoincrement then you have to provide the value or the insert will fail.
If you have defined userID in table2 as foriegn key constraint, then you will need to have the corresponding userID in the table1 as reference when inserting rows to table2, else if you have not defined any such constraints, then it will not matter.
Keep in mind, if the constraint is defined, then table2 will not generate ID by itself. It would require the ID to be present in the table1 column which is referenced.
If username and password is not null then don't insert in tabel 1 and give error