加入两个表并找到10个最大平均值

时间:2015-11-25 17:04:09

标签: mysql

我正在开发一个商业评论系统。 business表是 -

id     category
1         1
2         1
3         1
4         2

review表是 -

id     bid     reviewer_point
1       1             4
2       1             3
3       2             4
4       2             5

我需要退回最高评分(基于评分点平均值)业务的10 business ID个。

到目前为止,我可以找到每项业务的平均评分。 SELECT COUNT(reviewer_point) AS COUNT, AVG(reviewer_point) AS average FROM reviews WHERE bid = 1 我怎样才能得到我的首选解决方案。提前致谢

2 个答案:

答案 0 :(得分:2)

按平均降序排序并使用LIMIT子句

SELECT bid, AVG(reviewer_point) AS average 
FROM reviews 
GROUP BY bid
ORDER BY average DESC
LIMIT 10

编辑 - 如果您只想针对特定类别执行此操作: -

SELECT reviews.bid, AVG(reviews.reviewer_point) AS average 
FROM reviews 
INNER JOIN categories
ON reviews.bid = categories.id
WHERE categories.category = 1
GROUP BY reviews.bid
ORDER BY average DESC
LIMIT 10

答案 1 :(得分:1)

除非我遗漏了某些内容,否则您的解决方案似乎不需要类别。

它会像:

var path              = require('path');
var webpack           = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

var SRC_PATH    = path.join(__dirname, 'src');
var BUILD_PATH  = path.join(__dirname, 'dist');
var HTML_OPTS   = {
  filename: 'index.html',
  title:    'My Page Title',
  inject:   true,
  minify:   { collapseWhitespace: true, },
  templateContent: "<!DOCTYPE html>" +
    "<html>" +
      "<head>" +
        "<meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1'>" +
        "<meta charset='utf-8'/>" +
        "<title>{%= o.htmlWebpackPlugin.options.title %}</title>" +
      "</head>" +
      "<body>" +
      "</body>" +
    "</html>"
};

module.exports = {
  context:  SRC_PATH,
  entry:    [path.join(SRC_PATH, 'entry.js')],
  resolve:  {
    root:       SRC_PATH,
    extensions: ['', '.js', '.jsx']
  },
  output:   {
    path:       BUILD_PATH,
    filename:   'index.js'
  },
  plugins: [
    new HtmlWebpackPlugin(HTML_OPTS),
    new ExtractTextPlugin('public/bundle.css', {
            allChunks: true
        })
  ],
  module:   {
    loaders:  [
      {
        test:     /\.scss$/,
        loader:  ExtractTextPlugin.extract('style', 'css!sass')
      },
      {
        test:     /\.jsx?$/,
        exclude:  /node_modules/,
        loader:   'babel',
        query:
          {
            presets:['react']
          }
      }
    ]
  },
  sassLoader: {
    includePaths: [path.resolve(path.join(__dirname, "src"))]
  }
};