MySQL Использовать оператор WHERE для определения целевой строки - PullRequest
0 голосов
/ 27 февраля 2019

enter image description here Я пытаюсь запросить таблицу, которая сосредоточена на 3 разных столбцах.У меня есть столбцы NID, VID и заголовок.Мне нужно пройти через каждое значение nid, взять самый высокий vid каждого значения nid, как только я получу самый высокий vid, мне нужно получить заголовок, который находится в той же строке vid.В конечном итоге мне понадобится список каждого названия.У меня есть первые два шага вниз.Единственная часть, с которой мне нужна помощь, это получение правильного содержимого заголовка, потому что это должен быть заголовок, который находится в той же строке, что и самый высокий vid.Я думал, что утверждение «где» будет хорошим способом сделать это, но я застрял.Прикреплен скриншот таблицы.

$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]

1 Ответ

0 голосов
/ 27 февраля 2019

Подумайте о том, чтобы запустить агрегатный запрос (исключив любую ссылку на title ), которая присоединяется к таблице уровня объекта.Ниже возвращается title , соответствующий наибольшему vid для каждого 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
...