MySQL使用WHERE语句来定位特定行

问题描述 投票:-1回答:1

enter image description here我试图查询一个专注于3个不同列的表。我有列nid,vid和标题。我必须遍历每个nid值,获取每个nid值的最高视频,一旦我获得最高的视频,我就必须获得与视频的同一行中的标题。最终,我需要一个每个标题的列表。我有前两步了。我需要帮助的唯一部分是获取正确的标题内容,因为它必须是与最高vid在同一行中的标题。我认为where声明是一个很好的方法,但我被卡住了。附件是该表的屏幕截图。

$queryNodeRevision = "SELECT nid, MAX(vid) as vid, title FROM node_revision WHERE title = vid 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

下面是我正在尝试用我的代码完成的where语句。

$queryNodeRevision = "SELECT nid, MAX(vid) as vid, title FROM node_revision WHERE title = vid GROUP BY nid";[![enter image description here][1]][1]
php mysql sql where
1个回答
1
投票

考虑运行连接回单元级表的聚合查询(省略对标题的任何引用)。下面返回与每个nid的最高视频对应的标题。

SELECT n.nid, n.vid, n.title
FROM node_revision n
INNER JOIN
   (SELECT nid, MAX(vid) as max_vid 
    FROM node_revision 
    GROUP BY nid
   ) AS agg
ON agg.nid = n.nid AND agg.max_vid = n.vid
© www.soinside.com 2019 - 2024. All rights reserved.