How to make SQL many-to-many same-type relationship table -
i'm newbie sql , i'm jumping in head first trying learn as possible i'm coding, difficult i'm designing database i'll have live while want make sure right. learned basics of many-to-many bridge tables, if 2 fields same type? let's social network thousands of users, , how create table keep track of friends who? if there additional data each relationship, say... "date friended" example. knowing there queries "show friends of userx friended between datey , datez". database have several situations , can't figure out efficient way it. since it's coming lot me, figure others have figured out best way design tables, right?
create user table relationships table store id of 2 friend , kind of information relationship.
sql diagram

mysql code
create table `users` ( `id` tinyint not null auto_increment default null, primary key (`id`) ); create table `relationships` ( `id` tinyint not null auto_increment default null, `userid` tinyint null default null, `friendid` tinyint null default null, `friended` timestamp not null default current_timestamp, primary key (`id`) ); alter table `relationships` add foreign key (userid) references `users` (`id`); alter table `relationships` add foreign key (friendid) references `users` (`id`); sql selection
after fill tables data, can create sql select query of friends. friends id in 1 side side while id in other side. check both sides id don't need store relationships twice. have exclude id, because can't own friend (in normal, healthy world).
select * users u inner join relationships r on u.id = r.userid inner join relationships r on u.id = r.friendid (r.userid = $myid or r.friendid = $myid) , r.friended >= $startdate , r.friended <= $enddate , u.id != $myid; where $myid, $startdate , $enddate can php variables in double quotes can pass code directly database.
Comments
Post a Comment