【发布时间】:2013-09-21 11:03:11
【问题描述】:
我创建了一个“推荐好友”的 php 脚本,类似于 facebook。我的数据库有 2 个表,users(user_id, name, surname, profile) 和 friends(friends_id, user_one, user_two)。我的代码如下:
<?php
//----- gets all friends of my friends -------
$friends_of_friends = mysql_query(" SELECT u.*
FROM (SELECT DISTINCT user_one as user_id
FROM friends
WHERE user_two IN (SELECT user_one as user_id
FROM friends
WHERE user_two = '$session_user_id'
UNION DISTINCT
SELECT user_two
FROM friends
WHERE user_one = '$session_user_id'
)
UNION DISTINCT
SELECT DISTINCT user_two
FROM friends
WHERE user_one IN (SELECT user_one as user_id
FROM friends
WHERE user_two = '$session_user_id'
UNION DISTINCT
SELECT user_two
FROM friends
WHERE user_one = '$session_user_id'
)
) f
JOIN users u
ON u.user_id = f.user_id ");
while ($run_friends= mysql_fetch_assoc($friends_of_friends)) {
$friend_friend_id = $run_friends['user_id'];
// ---- gets friends of my friends that are not my friends -------------------------------
$check_friend_query = mysql_query(" SELECT friends_id from friends WHERE (user_one='$session_user_id' AND user_two='$friend_friend_id') OR (user_one='$friend_friend_id' AND user_two='$session_user_id') ");
if (mysql_num_rows($check_friend_query) != 1){
$not_friends = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE (`user_id`='$friend_friend_id' AND `user_id`!='$session_user_id') ");
while ($run_not_friends= mysql_fetch_assoc($not_friends)) {
$not_friend_id = $run_not_friends['user_id'];
echo $not_friend_id;
} //end while
} //end if
} //end while
?>
我的代码运行良好,并为我提供了我想要的所有朋友的朋友。是否可以将上述所有代码组合在一个 spl 语句中?知道怎么做吗?
【问题讨论】:
-
知道如何编写一个 mysql 语句来选择我朋友的朋友吗?
-
"是否有可能将以上所有代码合并到一个 spl 语句中?" -- 答案很可能是肯定的,但是从查询的性质来看,我认为执行查询会非常慢。至少比在几个查询中完成要慢很多。
-
好的,谢谢您的回答。我希望在一个 mysql 语句中执行此操作的原因是想使用 LIMIT 来获取我朋友的前 4 个朋友。所以这样写: $not_friends = mysql_query("SELECT
user_id,name,surname,email,profileFROMusersWHERE (user_id='$friend_friend_id' AND @98765=4330@! '$session_user_id') 限制 4; ");它不工作。我发现为了使用 LIMIT 应该从表中选择一个主要选项。就我而言,使用后我使用了许多选择和 if 语句,使我无法应用 LIMIT。 -
我相信我之前看到了您提出的问题,您在上面询问了问题。对于我认为它返回的内容,该查询似乎非常复杂。我不记得你是否在那个问题中给出了
users和friends的表格布局。如果您这样做了,您能否提供该问题的链接,或者以其他方式将表格布局(仅当相关字段非常大时)添加到该问题? -
我试图为“我朋友的朋友”申请分页,但没有成功。也许你的意思是:stackoverflow.com/questions/18915122/…
标签: php