我想实现这个
- john - >子用户
- john - >子用户
- 标记 - >子用户
- 标记 - >子用户
- 戴夫 - >子用户
- 戴夫 - >子用户
但这是意外的输出
- john - >子用户
- john - >子用户
仅显示用户名john
// Get all the users
$s = $sqlConnection->query('SELECT * FROM accounts');
while ($row = $s->fetch_assoc())
{
$uarr = explode(',', $row['username']);
foreach ($uarr as $ueach)
{
// Get all the direct sales
$query = "SELECT *";
$query .= " FROM accounts ACC";
$query .= " INNER JOIN info INF ON ACC.user_id = INF.iuid";
$query .= " INNER JOIN sales SAL ON ACC.user_id = SAL.suid";
$query .= " WHERE SAL.mentor = '$ueach'";
$s = $sqlConnection->query($query);
if (!$s)
{
die($sqlConnection->error);
}
while ($row = $s->fetch_assoc())
{
echo $ueach . ' -> ' . $row['username'] . '<br/>';
}
}
}
这是数据库结构
账户
user_id | username |
--------+----------+
1 | john |
--------+----------+
2 | mark |
--------+----------+
3 | dave |
--------+----------+
信息
iuid |
---------+
1 |
---------+
2 |
---------+
3 |
---------+
销售
suid | mentor |
--------+----------+
1 | john |
--------+----------+
2 | mark |
--------+----------+
3 | dave |
--------+----------+
答案 0 :(得分:5)
您可以使用一个查询获取所有数据,而不是使用两个。由于JOIN,您需要的数据随时可用:
SELECT SAL.mentor AS mentor, ACC.username AS username
FROM accounts ACC
LEFT JOIN info INF ON ACC.user_id = INF.iuid
LEFT JOIN sales SAL ON ACC.user_id = SAL.suid
ORDER BY SAL.mentor
当您返回行时,您可以使用$row['mentor']
和$row['username']
。
$query = "SELECT SAL.mentor AS mentor, ACC.username AS username ";
$query .= "FROM accounts ACC ";
$query .= "LEFT JOIN info INF ON ACC.user_id = INF.iuid ";
$query .= "LEFT JOIN sales SAL ON ACC.user_id = SAL.suid ";
$query .= "ORDER BY SAL.mentor ";
$s = $sqlConnection->query($query);
if (!$s)
{
die($sqlConnection->error);
}
else
{
while ($row = $s->fetch_assoc())
{
echo $row['mentor'] . ' -> ' . $row['username'] . '<br/>';
}
}
答案 1 :(得分:2)
您重新分配结果集覆盖$s
为内循环查询选择一个不同的变量
$second = $sqlConnection->query($query);