PHP根据同一表中另一列的值查询表列

时间:2019-02-27 02:31:43

标签: php mysql sql database

enter image description here我有一个数据库,必须使用PHP进行查询。我正在处理3个不同的列。我需要做的步骤仅需几个步骤,因此我将按步骤1列出...... 1)我必须仔细检查“ nid”列中的每个值。但是,某些“小人物”具有重复的价值。因此,我必须选择“ vid”值最高的“ nid”。 2)一旦我选择了具有最高“ vid”值的“ nid”,我就必须获取最高“ vid”的同一行中“ title”列的值。例如,如果我具有“ vid” 1253,则必须选择与“ vid” 1253对应的列标题中的内容。 我有很多步骤。但是,一旦抓到最高的vid,便会陷入困境,因为它能够抓取title列中的内容。下面是我的代码

<?php
    // Establish all database credential variables
    $serverName = "localhost";
    $username = "root";
    $password = "root";
    $databaseName = "redesign_static";
    // Create Database Connection
    $connection = new mysqli($serverName, $username, $password, $databaseName);
    // Check Database Connection
    if ($connection->connect_error) {
      die("Connection failed:" . $connection->connect_error);
    } // line ends if statement
    $queryNodeRevision = "SELECT nid, vid, title FROM node_revision";
    // line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
    $results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
    // line above creates variable $results > actually queries that database and passes in variable "$queryNodeRevision"
    $storeNIDAndVIDValues = []; // empty array to store max 'vid' values

    for ($i = 0; $i < 8000; $i++) {
      $storeNIDAndVIDValues[$i] = 0;
      // line above assigns initial 'vid'; starts at 0
    }

    while ($row = mysqli_fetch_array($results)) {
      $currentNID = $row['nid'];
      // line above creates variable that represents the current 'nid' of row (aka the key)
      $currentVID = $row['vid'];
      // line above creates variable that represents the current value of the 'vid' (the number you want to compare)
    if ($currentVID > $storeNIDAndVIDValues[$currentNID]) {
        // if the value of'$currentVID' is greater than what's stored in array '$storeNIDAndVIDValues' at current nid position
        // $storeNIDAndVIDValues[$currentNID] = goes into array $storeNIDAndVIDValues and gets the value of nid key (in this case value represents what position the nid is at)
           $storeNIDAndVIDValues[$currentNID] = $currentVID;
           // line above > becomes max 'vid' at that time 
           $titleOfSelectedVID = $row['title'];
          // $row['title'] = gets the value of the current 'title'
        $queryTitle = "SELECT title FROM node_revision WHERE $currentVID ";
        // line above is query variable that targets 'title' column row that has highest 'vid' value
     } // line ends if statement
    } // line closes while loop
  ?>

$queryTitle = "SELECT title FROM node_revision WHERE

$ queryTitle行是我遇到的问题。这是我要获取title列的内容的地方,但仅获取与最高vid对应的标题。

1 个答案:

答案 0 :(得分:0)

尝试如下编写查询

SELECT a.* FROM node_revision as a INNER JOIN (SELECT MAX(vid) as vid, nid FROM node_revision GROUP BY nid) as b on a.nid = b.nid WHERE a.vid = b.vid