我有点问题......
所以我要做的就是:
我有一个用户表:
-------------------------
| Table: userlist |
-------------------------
| Id | GuestOf | User |
|-----------------------|
| 0 | System | Bill |
|-----------------------|
| 1 | Bill | Jason |
|-----------------------|
| 2 | Jason | Jack |
|-----------------------|
| 3 | Jason | Jill |
|-----------------------|
| 4 | Jack | Matt |
|-----------------------|
| 5 | Jill | Stu |
|-----------------------|
| 6 | Jack | Gwen |
|-----------------------|
| 7 | Jill | Frank |
|-----------------------|
基本上,Jason的客人是Jack和Jill,Jack的客人是Matt和Gwen,而Jill的客人是Stu和Frank。
现在我要做的是找出Jason的客人是否有两位客人。
但是每次将新访客添加到列表中时我都只能检查这一点。在这种情况下,当Jill将Frank添加到列表中时。
这是我目前正在使用的代码:
function countGuests($User) {
$sql = "SELECT COUNT(`Id`) CntId FROM `userlist` WHERE `GuestOf` LIKE '$User'";
$res = mysql_query($sql);
$temp = mysql_fetch_array($res, MYSQL_BOTH);
return $temp["CntId"];
}
function checkCompletion($UserId) {
$population = array();
$sql = "SELECT `User` FROM `userlist` WHERE `GuestOf` LIKE '$UserId'";
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) {
while ($temp = mysql_fetch_array($res, MYSQL_BOTH)) {
$population[] = $temp["User"];
}
$partialPop = 0;
for ($i = 0; $i < count($populaton); ++$i) {
$partialPop = $partialPop + countGuests($population[$i]);
}
}
return $partialPop;
}
哪个应该给我结果:7(Jason,Jack,Jill,Matt,Gwen,Stu,Frank)
然而,我得到了结果:0。我的查询出了什么问题?
我将不胜感激任何帮助/更正......
谢谢!
答案 0 :(得分:1)
请考虑以下事项。我已经更改了列/表名称以简化概念化......
DROP TABLE IF EXISTS guestlist;
CREATE TABLE guestlist
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,user VARCHAR(12) NOT NULL
,guest VARCHAR(12) NOT NULL
,UNIQUE(user,guest)
);
INSERT INTO guestlist VALUES
(1,'System','Bill'),
(2,'Bill','Jason'),
(3,'Jason','Jack'),
(4,'Jason','Jill'),
(5,'Jack','Matt'),
(6,'Jill','Stu'),
(7,'Jack','Gwen'),
(8,'Jill','Frank');
SELECT a.user
, a.guest
, GROUP_CONCAT(b.guest) guest_of_guest
, COUNT(*) total
FROM guestlist a
LEFT
JOIN guestlist b
ON b.user = a.guest
WHERE a.user = 'Jason'
GROUP
BY user
, guest;
+-------+-------+----------------+-------+
| user | guest | guest_of_guest | total |
+-------+-------+----------------+-------+
| Jason | Jack | Gwen,Matt | 2 |
| Jason | Jill | Frank,Stu | 2 |
+-------+-------+----------------+-------+
2 rows in set (0.00 sec)
答案 1 :(得分:0)
如果问题是你必须遍历分层表中的所有节点,你应该考虑递归函数而不是迭代函数。
以下是检索所有用户(包括系统)列表的函数概要:
你必须用一个空数组调用这个函数,我希望结果在同一个数组中返回,但我不确定它是否是php中的情况....
function retrieveAllUsers($UserId, $population) {
$sql = "SELECT `User` FROM `guestlist` WHERE `Guest` LIKE '$UserId'";
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) {
temp = mysql_fetch_array($res, MYSQL_BOTH);
// traverse the array $temp
// in every iteration....
// push into $population the value $temp["User"];
retrieveAllUsers( $currentUser, $population );
}
}
}