【问题标题】:Retrieve user profile data from all of a user's friends using php and mysql使用 php 和 mysql 从用户的所有朋友中检索用户配置文件数据
【发布时间】:2014-05-01 02:35:22
【问题描述】:

我在网上搜索了几个例子,研究后仍然需要一些帮助。 我有 2 个表:用户和朋友。

users 表有列:

  • id bigint(20)UNSIGNED AUTO_INCREMENT
  • 用户名 varchar(50)
  • profile_picture varchar(200)
  • 状态 varchar(20)
  • status_message varchar(200)

朋友表有列:

  • id bigint(20) UNSIGNED AUTO_INCREMENT
  • initiator_user_id bigint(20)
  • friend_user_id bigint(20)

我希望能够从指定用户 (initiator_user_id) 的所有朋友 (friend_user_id) 的用户那里获取用户名、profile_picture、status、status_message。经过研究,我认为这是通过工会完成的。

我尝试了下面的查询,但它不起作用:

SELECT friend_user_id 
FROM friends
WHERE initiator_user_id = 1001 //gets all the id's of the friends of user 1001
UNION All
SELECT profile_picture, status, status_message, username from users
WHERE friend_user_id = id //gets all the profile data of user's profiles that are friends of user 1001

我需要为所有朋友显示朋友数据:

  • id bigint(20)UNSIGNED AUTO_INCREMENT
  • 用户名 varchar(50)
  • profile_picture varchar(200)
  • 状态 varchar(20)
  • status_message varchar(200)

我的问题:

  • 是否需要对表进行任何更改(任何外键约束等)?
  • 我需要进行哪些更改才能使此示例正常运行?

【问题讨论】:

  • 不,这不是使用 UNION 完成的。它是使用 JOIN 完成的。

标签: php mysql


【解决方案1】:

使用简单的 INNER JOIN:

SELECT u.*
FROM users AS u
INNER JOIN friends AS f ON f.friend_user_id = u.id
WHERE f.initiator_user_id = 1001

【讨论】:

  • 非常感谢这一切都很好。现在我唯一不明白的是为什么开发人员要添加外键约束和相关的东西。添加这种类型的约束有什么好处吗?
  • 它允许数据库确保数据是正确的。如果尝试创建指向不存在用户的朋友的代码中存在错误,则数据库将报告错误。这称为参照完整性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
相关资源
最近更新 更多