SQL内部联接2个表:基于组的AVG

时间:2018-09-10 00:08:49

标签: sql sqlite

我有2个表:电影和具有以下模式的演员表:

movies: | id | name | score |
cast:   | movie_id | cast_id | cast_name | 
-- cast.movie_id corresponds with movies.id

在某些情况下,我想找到平均电影得分最高的演员表(分数<40的电影应被忽略,所选的演员表应出现在2部以上的电影中)。这就是我现在拥有的:

SELECT c.cast_id, c.cast_name, AVG(m.score) AS average_score FROM movies AS m
INNER JOIN 
    (SELECT * FROM cast GROUP BY cast_id HAVING COUNT(cast_id) > 2) AS c
ON m.id == c.movie_id
GROUP BY c.cast_id
HAVING m.score >= 40
ORDER BY AVG(m.score) DESC, c.cast_name ASC
LIMIT 10;

但是当我检查结果时,例如对于某些演员,输出的平均得分为100.0,但他的电影的得分分别为100、100、85。我可以知道上面的SELECT语句出了错吗?

1 个答案:

答案 0 :(得分:0)

您可以这样表达:

SELECT c.cast_id, c.cast_name, AVG(m.score) AS average_score 
FROM movies m INNER JOIN
     cast c
     ON m.id = c.movie_id INNER JOIN
     (SELECT c.cast_id
      FROM cast c
      GROUP BY c.cast_id 
      HAVING COUNT(*) > 2  -- Only need `COUNT(DISTINCT c.movie_id)` if a person can be in one movie more than once
     ) cc
     ON cc.cast_id = c.cast_id
WHERE m.score >= 40
GROUP BY c.cast_id, c.cast_name
ORDER BY average_score DESC, c.cast_name
LIMIT 10;

注意:

  • 子查询用于计算给定演员的电影数量。
  • 需要JOINcast的附加HAVING以获得ID和名称。
  • 不需要var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt'); var userSchema = new Schema({ teamName: { type: String, unique: true, trim: true, required: true }, faculty: { type: String, required: true }, email: { required: true, unique: true, trim: true, type: String }, password: { required: true, type: String }, score: { type: Number, default: 0 } }); userSchema.pre('save', function(next) { var user = this; bcrypt.hash(user.password, 10, function(err, hash) { if (err) return next(err) user.password = hash; next(); }); }); userSchema.statics.authenticate = (email, password, callback) => { userModel.findOne({email: email}, (err, user) => { if (err) return callback(err); else if (!user) { console.log('User not found!') } else { bcrypt.compare(password, user.password, (err, result) => { if (result) { callback(null, true) } else { return callback() } }) } }) } var userModel = mongoose.model('User', userSchema); module.exports = userModel; 子句。