我想知道如何将这3个查询加在一起,因为我只想要一个JSON输出,我想INNER JOIN会这样做。但不知道如何使用它。有人可以指导我走上正确的道路吗?
$json = array();
$following_string = mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="SELECT * FROM streamdata WHERE streamitem_id < '$lastID' AND streamitem_target=".$following_string." OR streamitem_creator=".$following_string." ORDER BY streamitem_id DESC LIMIT 10";
$chant = mysqli_query($mysqli, $call) or die(mysqli_error($mysqli));
$json['streamdata'] = array();
while ($resultArr = mysqli_fetch_assoc($chant)) {
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['streamdata'] = $json;
}
/***** COMMENTS *****/
$check = "SELECT comment_id, comment_datetime, comment_streamitem, comment_poster, comment_content FROM streamdata_comments WHERE comment_poster=".$following_string." ";
$check1 = mysqli_query($mysqli,$check);
$json['streamdata_comments'] = array();
while ($resultArr = mysqli_fetch_assoc($check1)) {
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['streamdata_comments'] = $json;
}
/***** USERS *****/
$check = "SELECT * FROM users WHERE id=".$following_string."";
$check1 = mysqli_query($mysqli,$check);
$json['users'] = array();
while ($resultArr = mysqli_fetch_assoc($check1)) {
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
$json['users'] = $json;
}
echo json_encode($json);
}
?>
答案 0 :(得分:2)
您正在获取不相关的数据,因此您无法在SQL级别使用联接。
但JSON不关心你喂它什么,或者怎么样。只需构建适当的PHP级数据结构,例如
$data = array();
$data['streamdata'] = array();
... insert data from 'streamdata' query...
$data['streamdata_comments'] = array();
... insert comment data ...
$data['users'] = array();
... insert user data ...
将为您提供包含每个查询数据的3向数组。然后,您将整个$data
结构传递给json_encode,并且繁荣 - 您在单个数据结构中获得了3个未分级查询,而不是每次都接触SQL连接。
答案 1 :(得分:0)
您正在获取不相关的数据。只有当要连接的数据具有关系时,才能使用连接数据。
你不能加入苹果,牛和猴子。
答案 2 :(得分:0)
之前的一些答案表明您无法加入不相关的表,但这些表显然不是不相关的表。 streamdata
和streamdata_comments
表密切相关,users
表将其他表中的用户ID值映射到名称。
在SQL级别,可以轻松组合这些:
SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_ID = c.comment_streamitem
JOIN users AS u ON u.user_id = c.comment_poster
WHERE c.comment_poster = '$following_string'
AND d.streamitem_id < '$lastID'
AND (d.streamitem_target = '$following_string' OR
d.streamitem_creator = '$following_string');
将结果包装到JSON字符串中是否有意义是另一回事,我无法对其进行说明。这将为每条流项目的每条评论的评论信息提供一条记录。