while循环中的多选查询

时间:2016-08-28 08:00:36

标签: php mysql mysqli

用户表中的963行
视频表中的872行

在用户表(fbid,name)中是列名
在视频表(fbid等)中是列名。

使用以下查询,我通过从视频表提供fbid从用户表中获取名称。下面的查询只返回791行,​​但它应该返回872行。

<?php
$counter = 1;
$q = "SELECT * FROM videos GROUP BY fbid ORDER BY score DESC, id ASC";
$r = mysqli_query($conn,$q);
if(mysqli_num_rows($r)>0): 
    while($row = mysqli_fetch_assoc($r)):
        $fbid=$row['fbid'];

        $q1 = "SELECT name FROM users WHERE fbid=".$fbid."";
        $r1 = mysqli_query($conn,$q1);
        while($row1 = mysqli_fetch_assoc($r1)):
            $name=$row1['name'];
            ?>

            <?php
            $counter++;
        endwhile;
    endwhile;
endif;
?>

3 个答案:

答案 0 :(得分:1)

SELECT v.* 
     , u.name
  FROM videos v
  JOIN users u
    ON u.fbid = v.fbid
  ORDER 
    BY v.score DESC
     , v.id ASC;

答案 1 :(得分:0)

表格持有81(872-791)fbid。

替换此查询

$q = "SELECT * FROM videos GROUP BY fbid ORDER BY score DESC, id ASC";

使用:

$q = "SELECT * FROM videos ORDER BY score DESC, id ASC";

你将得到872

答案 2 :(得分:0)

我修改了您的查询代码

<?php

$counter = 0;
$q = "SELECT DISTINCT * FROM `videos`  ORDER BY `fbid` ASC";
$r = mysqli_query($conn,$q);
if(mysqli_num_rows($r)>0): 
while($row = mysqli_fetch_assoc($r)):
$fbid=$row['fbid'];

$q1 = "SELECT * FROM `user` WHERE `fbid`= $fbid ";
$r1 = mysqli_query($conn,$q1);
while($row1 = mysqli_fetch_assoc($r1)):
$name=$row1['nombre'];
echo $name . "<br/>;
?>

<?php
$counter++;
endwhile;
endwhile;
endif;

echo "Total " .$counter;
?>
如果你去791结果可能是因为某些视频fbid表不在表中检查这个查询有多少用户

SELECT count(fbid) FROM `videos` where  fbid NOT IN(SELECT fbid FROM `user`);