tags:

views:

60

answers:

1

How can I display the users friends correctly on the users and friends side using my MySQL tables? My current code screws this up.

Users Friends Table

CREATE TABLE users_friends (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED UNSIGNED NOT NULL,
friend_id INT UNSIGNED NOT NULL,
friendship_status TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
date_created DATETIME NOT NULL,
PRIMARY KEY (id),
KEY user_id (user_id),
KEY friend_id (friend_id)
);

Users Table

CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NULL,
avatar VARCHAR(255) NULL,
password CHAR(128) NOT NULL,
PRIMARY KEY (user_id),
UNIQUE KEY (username)
);

My Current MySQL Code

SELECT users.*, users_friends.*
FROM users
INNER JOIN users_friends ON users.user_id = users_friends.friend_id 
WHERE (users_friends.user_id = '" . $user_id . "' 
OR users_friends.friend_id = '" . $user_id . "')
AND users_friends.friendship_status = 1
GROUP BY users_friends.date_created
+1  A: 

Try this query. This should give you all friends for a particular user based on your database relationship.

SELECT     A.user_id, A.friend_id, B.username, B.avatar
FROM         users_friends AS A 
INNER JOIN   users AS B 
ON A.friend_id = B.user_id 
AND A.user_id = @userToBeSearched

UNION

SELECT    A.friend_id, A.user_id, B.username, B.avatar
FROM         users_friends AS A 
INNER JOIN users AS B 
ON B.user_id = A.user_id 
AND A.friend_id = @userToBeSearched

Note : I have removed the Group By clause for now because

  1. I am afraid i do not quite understand your schema enough to make sense of why you would be grouping rows only by date_created

  2. Adding the grouping clause will involve making another nested table as you will not be able to select columns not in the Group Clause.

Data used to test:-

Table : user

user_id |username| avatar | password
1   A   AAAA
2   B   BBBB
3   C   CCCCC
4   D   DDDDD

Table : user_friends

id | user_id | friend_id | friendship_status | date_created 
1   1   2   1   Friday, October 22, 2010 3:09:44 PM
2   2   3   1   Friday, October 22, 2010 3:43:18 PM
3   2   4   1   Friday, October 22, 2010 3:43:26 PM
InSane
How can I turn `SELECT A.user_id, A.friend_id, B.username, B.avatarSELECT` to `SELECT users.*, users_friends.*`
blahit
Just change the SELECT part to SELECT A.*, B.* instead.However, since you have the user_id column in both tables, it might cause some problems as it will be ambiguous. I would suggest you actually put all the columns you need in both SELECT statements
InSane
okay thanks for the help.
blahit