使用 Join 和 GroupBy 计算行数 - mysql , knex

Counting the number of raws with Join and GroupBy - mysql , knex

我有这个 table:

table foo

id | bar_id | user_id
-----------------
1  |    3   |   1
2  |    5   |   1
3  |    6   |   2
4  |    5   |   1
5  |    3   |   2

table 栏

id | title | description
------------------------
3  | hey   |  desc1
5  | ola   |  desc 2
6  | vassup | desc 3

然后我有这个查询

const basequery = knex
  .select('bar.*')
  .from('bar')
  .join('foo', 'foo.bar_id', 'bar.id')
  .groupBy('foo.bar_id')
  .whereIn('foo.user_id', 1);

这将 return:

id | title | description
-----------------------
3  | hey   | desc 1
5  | ola   | desc 2

这是正确的。

基本上我在文件上多次重复使用该基本查询。

然后我想计算由此编辑的行数return。

basequery.clone().countDistinct(`bar.id as total`)

我期待的是:

id | title | description | total
--------------------------------
3  | hey   | desc 1      |  2

因为 foo table 上有 2 列 id = 1 并按 bar_id 分组。我想将第一个查询 return 的列数计算为 "total".

但是,return是这样的:

id | title | description | total
--------------------------------
3  | hey   | desc 1      |  1
5  | ola   | desc 2      |  2

如有任何帮助,我们将不胜感激

我不知道 Knex,但如果 Knex 与 Laravel 类似,那么您几乎肯定需要使用一些原始查询功能来获得您想要的输出。您在输出中想要的 total 只是查询本身中的记录总数。不幸的是,在没有 运行 实际查询的情况下,我们无法在 MySQL 中使用任何技巧来获得该计数。在下面的原始查询中,我使用了一个不相关的子查询来计算总数。

SELECT
    b.*,
    (SELECT COUNT(*) FROM (SELECT b.id FROM bar b INNER JOIN foo f ON f.bar_id = b.id
     WHERE f.user_id IN (1) GROUP BY f.bar_id) t) total
FROM bar b
INNER JOIN foo f
    ON f.bar_id = b.id
WHERE f.user_id IN (1)
GROUP BY f.bar_id

要清楚,上面SELECT列表中的子查询是这样的:

SELECT COUNT(*)
FROM
(
    SELECT b.id
    FROM bar b
    INNER JOIN foo f
        ON f.bar_id = b.id
    WHERE f.user_id IN (1)
    GROUP BY f.bar_id
) t