我想做一个联系页面。这是我的表结构:
Accounts Table:
1) id
2) User_id
3) Full_name
4) Username
5) Email
6) Password
Contacts Table:
1) My_id (This is the user who added friend_id)
2) Contact_id (this is the contact who was added by my_id)
3) Status
我的查询看起来像这样:
$sid = ID of user who is viewing;
$sql = "SELECT STRAIGHT_JOIN DISTINCT contacts.contact_id,
accounts.full_name FROM contacts INNER JOIN accounts
on contacts.contact_id = accounts.user_id WHERE
contacts.my_id = '$sid' OR contacts.contact_id = '$sid'";
问题在于它无法以正确的方式运作。我最终在查询中看到了我的名字(这意味着当我登录时,我会在联系人中看到我的姓名,而不是联系人姓名)。
如何解决这个问题?感谢。
答案 0 :(得分:2)
此处不需要STRAIGHT_JOIN
关键字。要获取联系信息,请使用第二个JOIN
到contacts
表,该表将其与帐户相关联。
SELECT
DISTINCT c.contact_id,
cn.full_name
FROM
accounts a
/* first join connects the adding user's id to records in contacts */
INNER JOIN contacts c ON a.user_id = c.My_id
/* second join connects contact list user ids back to names in accounts */
INNER JOIN accounts cn ON cn.user_id = c.Contact_id
WHERE a.User_id = '$sid'
答案 1 :(得分:1)
这个查询应该足够了:
SELECT DISTINCT contacts.contact_id, accounts.full_name
FROM contacts, accounts
WHERE (contacts.my_id = '$sid' AND contacts.contact_id = accounts.user_id)
OR (contacts.contact_id = '$sid' AND contacts.my_id = accounts.user_id)