这是我的数据库:
id | liker | ques_id
1 | 15 | 2342
2 | 22 | 2342
3 | 22 | 2311
4 | 15 | 2389
我需要得到的是所有喜欢ques_id
的人。所以结果应该是这样的:
Question 2342 has been liked by 15 and 22.
Question 2311 has been liked by 22 and so on
我当前的代码为每个liker和ques_id
生成单独的行:
$sqlq=mysql_query("SELECT * FROM likes");
while($rowq=mysql_fetch_array($sqlq)){
$qid=$rowq['ques_id'];
$sql=mysql_query("SELECT * FROM likes where ques_id='$qid'");
$num=mysql_num_rows($sql);
$cont='';
while($row=mysql_fetch_array($sql)){
$liker=$row['liker'];
$cont .="$qid being liked by $liker<br>";
}
echo $cont;
}
答案 0 :(得分:0)
我没有测试过这个,但它应该让你开始:
$sqlq=mysql_query("SELECT DISTINCT(ques_id) FROM likes");
$cont='';
while($rowq=mysql_fetch_array($sqlq)){
$qid=$rowq['ques_id'];
$sql=mysql_query("SELECT * FROM likes where ques_id='$qid'");
$num=mysql_num_rows($sql);
$row=mysql_fetch_array($sql)
$cont .= "$qid being liked by $liker ";
while($row=mysql_fetch_array($sql)){
$liker=$row['liker'];
$cont .= " and $liker";
}
$cont .= ".<br>";
}
echo $cont;
答案 1 :(得分:0)
你不需要对DB进行第二次查询,它只能迭代第一个结果。 例如,您可以收集所有与关键字数组中特定ques_id相匹配的关键字,其中关键字为ques_id,如下所示:
$mathces = array();
$sqlq=mysql_query("SELECT * FROM likes");
while($rowq=mysql_fetch_array($sqlq)){
$qid=$rowq['ques_id'];
$liker=$rowq['liker'];
$matches[ $qid ][] = $liker;
}
然后,您可以预先$mathces
数组并构建字符串。
foreach ($matches as $qid => $likers) {
$cont .= "$qid being liked by " . implode(' and ', $likers );
if (count($likers) == 1)
$cont .= ' and so on';
echo "$cont<br>";
}
我没有测试我的代码。它需要额外的验证(例如,在第二个循环中为$linkers
)
答案 2 :(得分:0)
SELECT GROUP_CONCAT(liker), ques_id FROM likes GROUP BY ques_id
这将为每个ques_id将每个liker组合在一起。 然后,您只需处理返回的行。
您应该避免使用mysql extension,因为它已被弃用;请改用PDO或mysqli。
$sql = 'SELECT GROUP_CONCAT(liker) as likes, ques_id FROM likes GROUP BY ques_id';
foreach ($conn->query($sql) as $row) {
printf('Question %s is liked by %s', $row['ques_id'], $row['likes']);
}