计数查询和子查询

时间:2019-10-25 14:33:16

标签: sql

此查询获取属于类别的线程ID,并返回属于这些线程的帖子数:

SELECT COUNT(*) 
FROM post p 
WHERE p.thread_id IN (SELECT t.id 
                      FROM thread t 
                      WHERE t.category_id = 1);

如何使此查询也将线程数(子查询数)添加到总数中?

2 个答案:

答案 0 :(得分:0)

这是您想要的吗?

SELECT 
    COUNT(*) cnt,
    COUNT(DISTINCT p.thread_id) cnt_threads
FROM post p 
WHERE p.thread_id IN (SELECT t.id FROM thread t WHERE t.category_id = 1);

此外,将IN与子查询一起使用也很棘手。如果子查询返回的任何值都是NULL,则没有一个值匹配。您的查询可能被重写为:

SELECT 
    COUNT(*) cnt,
    COUNT(DISTINCT p.thread_id) cnt_threads
FROM post p 
INNER JOIN thread t ON p.thread_id = t.id AND t.category_id = 1

答案 1 :(得分:0)

您可以使用窗口功能

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  output: {
    path: __dirname + '/dist',
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './dist'
  },
  mode: 'development'
};