MySQL查询显示问题

时间:2010-10-22 06:24:58

标签: php mysql

如何使用MySQL表在用户和朋友方面正确显示用户朋友?我目前的代码搞砸了。

用户朋友表

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

我当前的MySQL代码

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 个答案:

答案 0 :(得分:0)

尝试此查询。这应该根据您的数据库关系为您提供特定用户的所有朋友。

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

注意:我暂时删除了Group By子句,因为

  1. 我恐怕我不太了解你的架构,足以理解为什么你只能通过date_created对行进行分组

  2. 添加分组子句将涉及创建另一个嵌套表,因为您将无法选择不在组子句中的列。

  3. 用于测试的数据: -

    表:user

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

    表: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