简体   繁体   English

如何在两个相关的PHP MySQL查询中订购?

[英]How to order by in two PHP MySQL queries that are related?

I am creating a dropdown select form based on the results from two cross-referenced MySQL queries, however I cannot get the list to order by alphabet correctly. 我正在根据两个交叉引用的MySQL查询的结果创建一个下拉选择表单,但是我无法通过正确的字母顺序获取列表。

I am taking an ID number from the first table "list1", but then need to get its name from the second table "list2", and display them alphabetically. 我从第一个表“list1”中获取一个ID号,但是需要从第二个表“list2”获取其名称,并按字母顺序显示它们。

I tried the ORDER BY, but it does not make sense in either query really. 我尝试了ORDER BY,但它在任何一个查询中都没有意义。

    <select name="select">
        <?php
        $sql       = "SELECT DISTINCT id FROM list1"; 
        $query     = mysqli_query($connection, $sql) or die (mysqli_error()); 

        while ($row= mysqli_fetch_array($query)) { 
            $id        = $row["id"];
            // *** get the ID name from second table ***
            $sql2 = "SELECT * FROM list2 WHERE id='$id' ORDER BY name ASC LIMIT 1"; 
            $query2 = mysqli_query($connection, $sql2) or die (mysqli_error()); 

            while ($row2 = mysqli_fetch_array($query2)) { 
                $name = $row2["name"];
                echo '<option value="'.$id.'">'.$name.'</option>';
            } // end while

            // *** end get name ***

        } // end while
        ?>
    </select>

Just combine the two queries into one: 只需将两个查询合并为一个:

select col1, col2 etc
from list2 where list2.id in (SELECT DISTINCT id FROM list1)
order by name asc

This gives you the same list you would have gotten to using your queries and subsequent sub-queries but does it one go and you can order the whole result as needed. 这为您提供了使用查询和后续子查询所使用的相同列表,但只需一次就可以根据需要订购整个结果。

<select name="select">
<?php
  $sql2 = "    select col1, col2 etc
    from list2 where list2.id in (SELECT DISTINCT id FROM list1)
    order by name asc
"; 
  $query2 = mysqli_query($connection, $sql2) or die (mysqli_error()); 
  while ($row2 = mysqli_fetch_array($query2)) { 
  $name = $row2["name"];
  echo '<option value="'.$id.'">'.$name.'</option>';
  } // end while
?>
</select>

Just note that you should probably not use select * when joining tables like this. 请注意,在连接这样的表时,您可能不应该使用select * Just pick the columns you want. 只需选择您想要的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM