Using MYSQL Associative Table and JOIN -
here structure of 3 tables:
create table `contacts` ( `id` int(11) unsigned not null auto_increment, `name` varchar(99) default not null, primary key (`id`) ) engine=innodb auto_increment=1 default charset=latin1; create table `addresses` ( `id` int(11) unsigned not null auto_increment, `street` varchar(99) default not null, `city` varchar(99) default not null, `state` varchar(20) default not null, `zip` int(9) default not null, primary key (`id`) ) engine=innodb auto_increment=1 default charset=latin1; create table `contacts_addresses` ( `id` int(11) unsigned not null auto_increment, `idcontact` int(9) default not null, `idaddress` int(9) default not null, primary key (`id`) ) engine=innodb auto_increment=1 default charset=latin1;
sample data:
mysql> select * contacts; +----+----------------+ | id | name | +----+----------------+ | 1 | hank kingsley | | 2 | phil collins | | 3 | sam weisgamgee | | 4 | john johnson | | 5 | dale girdley | +----+----------------+ mysql> select * addresses; +----+--------------------+-----------+-------+-------+ | id | street | city | state | zip | +----+--------------------+-----------+-------+-------+ | 1 | rainbow lane | fairytown | vt | 52689 | | 2 | townie ave | manhattan | ny | 98569 | | 3 | sayitain'tso drive | oldsville | ky | 25689 | | 4 | somehow circle | anytown | tx | 84757 | +----+--------------------+-----------+-------+-------+ mysql> select * contacts_addresses; +----+-----------+-----------+ | id | idcontact | idaddress | +----+-----------+-----------+ | 1 | 3 | 1 | | 2 | 3 | 2 | | 3 | 5 | 3 | | 4 | 1 | 1 | | 5 | 4 | 2 | +----+-----------+-----------+
i trying run query let me specify unique contact's id, , pull associated addresses. i've been trying figure out couple of days, don't understand how joins work. other forums, articles, material haven't helped me illuminate particular issue.
am structuring tables correctly? should using foreign keys somewhere? using appropriate naming convention associative table/columns?
any appreciated, either solution or pseudo-code show structure of query - thank you.
for getting address 1 particular contact concatid 3 can as
select c.id, c.name, a.street, a.city, a.zip, a.state contacts_addresses ca join contacts c on c.id = ca.idcontact join addresses on a.id = ca.idaddress c.id = 3
to contacts remove last condition``
Comments
Post a Comment