1

我想做一个联系人页面。这是我的表结构:

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'"; 

问题是它不能以正确的方式工作。我最终在查询中看到我的名字(这意味着当我登录时,我在联系人中看到我的名字而不是联系人姓名)。

如何解决这个问题?谢谢。

4

2 回答 2

2

此处的STRAIGHT_JOIN关键字不应该是必需的。要获取联系信息,请使用第二个JOINcontacts其与帐户相关联的表。

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'
于 2012-05-08T01:40:52.593 回答
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)
于 2012-05-08T01:44:53.513 回答