while() 中的 while() 或 1x 查询?
while() in while() or 1x Query?
我不知道 PHP 和 SQL 哪种方式更好。
我设计并编写了自己的评论系统,我希望 id2=0 是一个评论,id2>0 是一个 table 中的子评论。这意味着如果有人在ID=1的评论中写了子评论,那么ID2负责分配(子评论)给ID=1(评论)。
我有一个 table comments
这样的:
id | id2 | smt | etc.
1 | 0 | x | x //comment with sub-comment where id=3
2 | 0 | x | x //comment
3 | 1 | x | x //that is sub-comment for comment where id=1
我在 while 循环中显示它,因为我需要打印评论中的所有数据。像这样:
$sqlkom="SELECT * FROM `comments` WHERE `id`='".$row['id']."' ORDER BY id DESC LIMIT 20";
if($resultkom = mysqli_query($con, $sqlkom)){
if(mysqli_num_rows($resultkom)){
while($rowkom = mysqli_fetch_assoc($resultkom)) {
echo HtmlFormatFunction($rowkom['id'],$rowkom['id2'],$rowkom['smt'],$rowkom['etc'])
如果不添加另一个 while() 循环,我将无法实现:if($rowkom['id']==$rowkom['id2'])
,对吗?
或者修改 SQL 查询就足以达到这种效果?请帮助我找到正确的解决方案。
你可以加入你的 table 和它自己,像这样:
SELECT c.id, c.id2, c.smt, c.etc,
s.id, AS s_id, s.id2 AS s_id2, s.smt AS s_smt, s.etc AS s_etc
FROM `comments` c LEFT JOIN `comments` s
ON c.id = s.id2
WHERE c.id = ?
ORDER BY c.id DESC LIMIT 20";
那么您应该为第一条评论获取最少一行,或者为第一条评论获取尽可能多的行数 sub-comments。然后前四个字段将重复,但这不是问题。也许这并不完美。希望你明白了。
我不知道 PHP 和 SQL 哪种方式更好。
我设计并编写了自己的评论系统,我希望 id2=0 是一个评论,id2>0 是一个 table 中的子评论。这意味着如果有人在ID=1的评论中写了子评论,那么ID2负责分配(子评论)给ID=1(评论)。
我有一个 table comments
这样的:
id | id2 | smt | etc.
1 | 0 | x | x //comment with sub-comment where id=3
2 | 0 | x | x //comment
3 | 1 | x | x //that is sub-comment for comment where id=1
我在 while 循环中显示它,因为我需要打印评论中的所有数据。像这样:
$sqlkom="SELECT * FROM `comments` WHERE `id`='".$row['id']."' ORDER BY id DESC LIMIT 20";
if($resultkom = mysqli_query($con, $sqlkom)){
if(mysqli_num_rows($resultkom)){
while($rowkom = mysqli_fetch_assoc($resultkom)) {
echo HtmlFormatFunction($rowkom['id'],$rowkom['id2'],$rowkom['smt'],$rowkom['etc'])
如果不添加另一个 while() 循环,我将无法实现:if($rowkom['id']==$rowkom['id2'])
,对吗?
或者修改 SQL 查询就足以达到这种效果?请帮助我找到正确的解决方案。
你可以加入你的 table 和它自己,像这样:
SELECT c.id, c.id2, c.smt, c.etc,
s.id, AS s_id, s.id2 AS s_id2, s.smt AS s_smt, s.etc AS s_etc
FROM `comments` c LEFT JOIN `comments` s
ON c.id = s.id2
WHERE c.id = ?
ORDER BY c.id DESC LIMIT 20";
那么您应该为第一条评论获取最少一行,或者为第一条评论获取尽可能多的行数 sub-comments。然后前四个字段将重复,但这不是问题。也许这并不完美。希望你明白了。