简体   繁体   中英

MySQL query display problem

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

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)
);

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)
);

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

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

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