简体   繁体   中英

Alter table with foreign key

I have three tables.

Person (id, FirstName, LastName, BirthDate)
Contact (id, contact, type)
PersonContact( Person_id, Contact_id )

As you can see that Person_id is comming from Person table in PersonContact table And Contact_id is comming from Contact table in PersonContact table

I want to write a query that should relate Person_id column of PersonContact table with id column of Person Table as foreign key.

And Contact_id column of PersonContact with id column of Contact table as foreign key

This should answer the problem

CREATE TABLE IF NOT EXISTS `person_contact` (
  `contact_id` int(11) NOT NULL,
  `person_id` int(11) NOT NULL,
  PRIMARY KEY (`contact_id`,`person_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;


ALTER TABLE `person_contact`
  ADD CONSTRAINT `person_contact_ibfk_2` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`),
  ADD CONSTRAINT `person_contact_ibfk_1` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`id`);

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

alter PersonContact add foreign key(PersonID) references Person(ID)

To select, you do:

select *
    from Person
        inner join PersonContact on(Person.ID=PersonContact.PersonID)

Here's my $0.02 worth of advise in terms of T-SQL

Select FirstName, LastName, BirthDate from Person p join PersonContact pc ON p.id= pc.Person_id

Select Contact, type From Contact c join PersonContact pc ON c.id= pc.Person_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM