tags:

views:

33

answers:

2

Hello,

I have a problem when using foreign keys and primary keys in MySQL datable.

Now I have two tables p1,p2.

create table p1(
    id int(10) not null auto_increment, 
    type_id int(10) default 1, 
    name varchar(20), 
    primary key(id, type_id)
    );
create table p2(
    id int(10) not null, 
    type_id int(10) not null, 
    name varchar(20), 
    primary key(id, type_id)
    );
alter table p1 add foreign key(id, type_id) references p2(id, type_id) on delete cascade;

When i insert values into p2, i want p1 to be updated with the values id, type_id inserted in p1.

insert into p2(name) values('p2');
set @temp = 0;
select last_insert_id() into @temp;
insert into p1(id, type_id, name) values(@temp, name);

How could i do this?

A: 

With MyISAM tables - noway. Insertion will be done always sequential. With InnoDb - use threads to execute queries.

Or may be you mean you need to do that in transaction?

FractalizeR
I tried to use transaction, but failed. Can you check where is wrong?
garcon1986
+1  A: 

You could set up triggers on p2 and p3.

Also, your insert query is broken. You specify three columns but only two values..

jasonbar
@jasonbar, because i don't know how to insert the three values into table p2.
garcon1986