Forum Moderators: open

Message Too Old, No Replies

Table Joins help

         

MrFahad

7:28 pm on Nov 19, 2008 (gmt 0)

10+ Year Member



Hello i have made a foreign key:

ALTER TABLE `tMobileHomes` ADD FOREIGN KEY ( `Propertyid` ) REFERENCES `casherzc_realestate`.`tProperty` (
`Propertyid`
);

but when i update Propertyid on table tProperty it dose not update on tMobileHomes, what I'm doing wrong

please help thanks

LifeinAsia

7:54 pm on Nov 19, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



A KEY is a type of index. Changing a value of a KEY does not by itself alter data in any other tables.

You need to setup a TRIGGER to accomplish what you apparently want to do.

ZydoSEO

3:42 am on Nov 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What your ALTER TABLE statement did was setup a rule that says basically:

Before you can insert a row in tMobileHomes for tMobileHomes.PropertyID=X there must first exist a row in in tProperty where tProperty.PropertyID=X.

So if you are adding a new property that is of type MobileHome then you would have to make two inserts to add that single property:

1) First insert a new row in tProperty with PropertyType=1 (if 1=MobileHome). If tProperty.PropertyID is an identity/autoincrement field then the DB will assign a unique value for PropertyID when it inserts the row in tProperty.
2) Get the identity/autoincrement PropertyID value that was created by the DB when you inserted the row in tProperty in step 1.
3) Next insert a new corresponding row into tMobileHomes with tMobileHomes.PropertyID = the identity/autoincrement PropertyID value from tProperty

Using SQL SERVER you would do something like

DECLARE @lvMyPropertyID INT

INSERT INTO tProperty (PropertyType, ListingPrice,...) VALUES (1, 25000,...)

SET @lvMyPropertyID=@@IDENTITY

INSERT INTO tMobileHomes (PropertyID, Width, Length,...) VALUES (@lvMyPropertyID, 14, 70,...)

This would create a property that is of type mobile home (assuming a PropertyType=1 means Mobile Home) with a listing price of $25,000. The SET command grabs the IDENTITY value created by the previous INSERT statement and assigns it to a local variable @lvMyPropertyID. The 2nd INSERT then adds that property to tMobileHomes with the Foreign Key reference to tProperty.PropertyID, a width of 14 ft, a length of 70 ft, etc.

MrFahad

6:47 am on Nov 21, 2008 (gmt 0)

10+ Year Member



what about MySQL how would i do it.

ZydoSEO

4:15 am on Nov 23, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




I think I've done enough of your homework. Surely you can translate what I've given you so far.