使用左联接时进行Mysqli转换

时间:2018-11-13 12:18:52

标签: php mysql mysqli

尝试转换为MySQLi。最近几天,我得到了很大的帮助,谢谢。我的下一个问题是使用LEFT JOIN时如何进行转换。

有效的MYSQL代码

$q1 = 'SELECT * FROM earth LEFT JOIN cities ON (cities.countryid4city = earth.countryid) GROUP BY countryid ORDER by countryid';
$q2 = 'SELECT * FROM cities ORDER BY cityname';
$mytable1 = mysql_query($q1);
$mytable2 = mysql_query($q2);
echo mysql_error();
mysql_close();
$numrows_table1 = mysql_numrows($mytable1); 
$numrows_table2 = mysql_numrows($mytable2);
$i = 0;
while ($i < $numrows_table1){
    $countryid = mysql_result($mytable1,$i,'countryid');
    $countryname = mysql_result($mytable1,$i,'countryname');
    print "<br><br>Country is " . $countryname . ", and these cities are in it";
    $j = 0;
    while ($j < $numrows_table2){
        $countryid4city = mysql_result($mytable2,$j,'countryid4city');
        $cityname = mysql_result($mytable2,$j,'cityname');
        if ($countryid4city == $countryid){
            print "<br><br>" . $cityname;
        }
        $j++;
    }
    $i++;
}

输出符合预期。 (请注意,该网站删除了其中的行分隔符,但它们在那里。)

Country is USA, and these cities are in it

New York

San Francisco

Country is England, and these cities are in it

Chelsea

Clapham

London


Country is Sweden, and these cities are in it

Lidingö
Stockholm

MYSQLI转换中断(我认为遵循相同的逻辑)

$q1 = 'SELECT * FROM earth LEFT JOIN cities ON (cities.countryid4city = earth.countryid) GROUP BY countryid ORDER by countryid';
$q2 = 'SELECT * FROM cities ORDER BY cityname';
$mytable1 = mysqli_query($conned, $q1);
$mytable2 = mysqli_query($conned, $q2);
mysqli_close($conned);
while($row1 = mysqli_fetch_assoc($mytable1)){
    $countryid = $row1['countryid'];
    $countryname = $row1['countryname'];
    print "<br><br>Country is " . $countryname . ", and these cities are in it";
    while($row2 = mysqli_fetch_assoc($mytable2)){
        $countryid4city = $row2['countryid4city'];
        $cityname = $row2['cityname'];
        if ($countryid4city == $countryid){
            print "<br><br>" . $cityname;
        }
    }
}

输出

Country is USA, and these cities are in it

New York

San Francisco

Country is England, and these cities are in it

Country is Sweden, and these cities are in it

它只是从第二个表中选取LEFT JOIN值作为第一个表中的第一个值。我想念什么?我收集到的信息可能不是理想的MYSQL版本解决方案。

任何帮助,我们将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

mysql_result使结果集可用作索引数组。 OTOH mysqli_fetch_assoc从结果中检索一行。虽然可以通过将光标移动到内循环之前记录集的开头来解决问题:

  mysqli_result_data_seek ($mytable2, 0);
  while($row2 = mysqli_fetch_assoc($mytable2)){

这只会增加运行第二个查询来检索您已经知道的数据的愚蠢性。将第一个查询更改为

 ...ORDER by countryid, cityname";

丢失第二个查询和内部循环。每当countryid更改时,在输出中插入一个新的country标头。