检索每个不同url_id的最新行

时间:2016-12-06 20:02:32

标签: mysql greatest-n-per-group

我有表格的结构

评论表:

function createNewSheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var masterSheet = spreadsheet.getSheetByName('master');

  // Retrieve 2d array for column A
  var colA = masterSheet.getRange('A:A').getValues();

  // Create a 1d array of unique values
  var uniqueValues = {};
  colA.forEach(function(row) {
    row[0] ? uniqueValues[row[0]] = true : null;
  });
  var newSheetNames = Object.keys(uniqueValues);

  newSheetNames.forEach(function(sheetName) {
    // Check to see whether the sheet already exists
    var sheet = spreadsheet.getSheetByName(sheetName);
    if (!sheet) {
      spreadsheet.insertSheet(sheetName);
    }
  });
}

网址表

id - grade - url_id
1     2       1
2     4       2
3     5       3
4     3       4
5     4       1
6     5       2
7     2       3

我想检索为每个url_id插入的最新成绩,并将其与urls表连接,如下所示:

id - url
1   www.google.com
2   www.apple.com
3   www.bing.com

这是我的尝试

id - grade - url_id - url
5     4       1       www.google.com
6     5       2       www.apple.com
7     2       3       www.bing.com

我收到此错误 SELECT a.id, a.reviews, a.url_id, b.url FROM ( SELECT id, grade, url_id FROM reviews ORDER BY id DESC ) AS a INNER JOIN urls ON a.url_id = urls.id GROUP BY a.url_id

如何编辑代码以使其有效?

除了禁用"Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'a.id' which is not functionally dependent on columns in GROUP BY clause"

之外,我不能说我通过搜索网络了解到了什么问题

2 个答案:

答案 0 :(得分:0)

如果您想要最新版本,则可以使用where子句进行过滤:

select r.*
from reviews r
where r.id = (select max(r2.id) from reviews r2 where r2.url_id = r.url_id);

如果有必要,您可以加入网址。

答案 1 :(得分:-1)

SELECT r.*
FROM reviews r
WHERE r.grade = ( SELECT Max(r2.grade) 
                FROM reviews r2  
                WHERE r2.url_id = r.url_id )
ORDER BY r.url_id