PHP如何查询数据库表中的所有行

时间:2019-02-27 17:27:30

标签: php sql mysqli datatable

我正在研究一个涉及PHP和SQL的项目。我必须查询表中的几列。对于前两列“ nid”和“ vid”,我得到了所有正确的值。但是,对于最后一列“标题”,查询仅返回第一行。例如,有nids 2、3、4,依此类推,但其中有些具有不止一项。而不是为2、3等的每个项目返回标题,而是仅返回第一个。这是为什么?随附的屏幕截图显示了我在说什么

$queryNodeRevision = "SELECT nid, MAX(vid) as vid, title FROM node_revision GROUP BY nid";
    // line above creates variable $queryNodeRevision > 

    $results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
    // line above creates variable $results > actually queries that database and passes in variable "$queryNodeRevision"

    while ($row = mysqli_fetch_array($results)) {
      // line above creates while loop that loops through > $row = mysqli_fetch_array($results)
      // $row is variable that's set to mysqli_fetch_array (with variable $results being passed in)
      // mysqli_fetch_array > creates an associate array for each row in a table
      // $results > variable that's being passed into associative array that represents the variable that's quering "SELECT nid FROM node_revision";
      $currentNID = $row['nid'];
      // line above creates variable that represents the current 'nid' of row (aka the key)
      // $row['nid'] = gets the key # of the current 'nid'
      $currentVID = $row['vid'];
      // line above creates variable that represents the current value of the 'vid' (the number you want to compare)
      // $row['vid'] = gets the value of the current 'vid'  
      $theTitleIWant = $row['title'];
      // line above creates variable that represents the current value of the 'title'
      // $row['title'] = gets the value of the current 'title'  
      echo "<h1>" . $row['title'] . "</h1>";
      // line prints out desired 'title' into h1 tag
    } // line closes while loop

以下是未正确定位所有标题的查询行:

$queryNodeRevision = "SELECT nid, MAX(vid) as vid, title FROM node_revision GROUP BY nid";

示例输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

对于您的预期结果,不需要Group by子句。 查询如下:

SELECT nid, (select MAX(vid) from node_revision nr1 where nr1.nid=nid) as vid, title FROM node_revision nr2 where nr2.nid=3

希望这对您有帮助