【问题标题】:How to create a contacts page properly?如何正确创建联系人页面?
【发布时间】:2012-05-16 11:53:52
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: php sql friend


    【解决方案1】:

    这里不需要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'
    

    【讨论】:

    • contacts.full_name 似乎不存在(至少不在 OP 提供的表格中)
    • 为了获得accounts.Full_name,连接似乎是必要的。但除此之外,一个可靠的答案! +1
    • @SetSailMedia 已修复 - 需要第二次加入
    • 嘿,使用你的我得到了这个错误:错误:表'database.accounts_accounts'不存在
    • @ariel 您是否完全按照当前版本使用当前版本?里面没有类似accounts_accounts
    【解决方案2】:

    这个查询应该足够了:

    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)
    

    【讨论】:

    • 是的,我从来没有通过将它们放入 CSV 列表中成功地从两个不同的表中进行选择。 (FROM contacts, accounts)
    • 你错了,或者没有使用正确的语句。你可以在 MySQL 手册中找到这个语法:dev.mysql.com/doc/refman/5.0/en/join.html,我已经在 MySQL 上的很多部署项目中使用了它。
    • 你是对的! :O 我刚试过。我想,唯一的区别是它们没有加入每个记录。
    • 使用你的代码给我这个错误:错误:表'database.accounts_accounts_accounts'不存在
    • 乐于助人!这将取决于表 3 的结构以及它如何链接在一起(表 3 的列值以及表 1 或 2 的列值),但您当然可以加入第三个表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2017-03-16
    • 2011-11-12
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多