【问题标题】:Count rows that have the same set of related records计算具有相同相关记录集的行
【发布时间】:2013-12-13 22:12:37
【问题描述】:

这可能很简单,但我无法弄清楚。这是我正在使用的表。

table_a

id  other_data
-------------
1      blah
2      foo
3      bar

table_b

ref_a  ref_c
-------------
1      1
1      2
2      3
3      3

table_c

id   name
----------
1    TestA
2    TestB
3    TestC

我想要得到的是这样的东西,我正在计算具有相同子集 (table_b) 的行数 (table_a)。我还希望能够从另一个表(table_c 的名称)中获取相关数据。

TestA,TestB 1
TestC       2

我知道它可能使用 Group By 和 GROUP_CONCAT,但我无法让它工作。

我试过了,但它不起作用。

SELECT GROUP_CONCAT(DISTINCT table_c.name separator ', ') as 'combo_text', COUNT(DISTINCT table_a.id) 来自table_a 内连接table_btable_a.id = table_b.ref_a 内连接table_ctable_c.id = table_b.ref_c 分组table_b.ref_a

【问题讨论】:

  • 请更好地格式化您的问题(您的示例数据和示例输出)
  • 您能否根据 Stack Overflow 的good question guidelines 编辑您的问题以包含您尝试过但不起作用的内容?

标签: mysql group-by group-concat


【解决方案1】:
SELECT a.id, count(a.id) as count, GROUP_CONCAT(name) as names
FROM table_a a
JOIN table_b b ON (a.id = b.ref_a)
JOIN table_c c ON (b.ref_c = c.id)
GROUP BY a.id

sqlFiddle demo

根据你的结果,你想要这样的东西

SELECT names, count(count) as count FROM
  (SELECT a.id, count(a.id) as count, GROUP_CONCAT(name) as names
   FROM table_a a
   JOIN table_b b ON (a.id = b.ref_a)
   JOIN table_c c ON (b.ref_c = c.id)
   GROUP BY a.id
  )T1
GROUP BY names

sqlFiddle demo

【讨论】:

  • 谢谢!在我改正我的问题之前你得到了正确的答案哈哈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 2014-04-21
相关资源
最近更新 更多