友谊表的MYSQL JOIN QUERY

时间:2012-01-06 16:04:35

标签: php mysql join

我有以下两个表

CREATE TABLE accounts (
 id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
 name VARCHAR(255) NOT NULL
);

CREATE TABLE friends (
 id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
 account_id INTEGER UNSIGNED NOT NULL,
 friend_id INTEGER UNSIGNED NOT NULL,
 created_on TIMESTAMP NOT NULL
);

我建立了一个JOIN查询:

SELECT accounts.name, accounts.id, friends.account_id FROM accounts
RIGHT JOIN friends ON accounts.id = friends.account_id
ORDER BY accounts.name LIMIT 10;

它看起来像:

迈克芬威| 1 | 3 |

吉姆莫里森| 3 | 1 |

问题是如何显示朋友姓名,以便结果如下:

迈克芬威| 1 |吉姆莫里森| 3 |

吉姆莫里森| 3 |迈克芬威| 1 |

2 个答案:

答案 0 :(得分:2)

您需要执行进一步的联接才能获取好友数据。我使用LEFT JOIN总是返回帐户,即使没有朋友也是如此。 INNER JOIN只会返回有朋友的帐户,而忽略那些没有朋友的帐户。

SELECT A.id, A.name, ACC.id `friendId`, ACC.name `friendName`
FROM accounts A
LEFT JOIN friends F ON A.id = F.account_id
LEFT JOIN accounts ACC ON F.friend_id = ACC.id
ORDER BY A.name LIMIT 10;

答案 1 :(得分:0)

SELECT
    MainAccount.Name as OwnerName,
    MainAccount.ID as OwnerID,
    COALESCE(AnotherMain.Name, '') as FriendName
    COALESCE(Friends.ID, '')  as FriendID
FROM
    Accounts as MainAccount 
        LEFT JOIN Friends ON
            MainAccount.ID = Friends.ID
        LEFT JOIN Accounts as AnotherMain ON
            Friends.ID = AnotherMain.ID
ORDER BY MainAccount.Name LIMIT 10