多对多计数

Counting many to many

我在 contactproject 之间有很多联系。

contact:
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
+-----------------+--------------+------+-----+---------+----------------+

project:
+-------------------+--------------+------+-----+---------+----------------+
| Field             | Type         | Null | Key | Default | Extra          |
+-------------------+--------------+------+-----+---------+----------------+
| id                | int(11)      | NO   | PRI | NULL    | auto_increment |
+-------------------+--------------+------+-----+---------+----------------+

project_contact:
+---------------+---------+------+-----+---------+-------+
| Field         | Type    | Null | Key | Default | Extra |
+---------------+---------+------+-----+---------+-------+
| project_id    | int(11) | NO   | PRI | NULL    |       |
| contact_id    | int(11) | NO   | PRI | NULL    |       |
+---------------+---------+------+-----+---------+-------+

我想统计有多少联系人与没有项目、一个项目或多个项目相关联。如果我能在一个查询中得到它,那绝对很棒,如果不能,3 个不同的查询也能做到。

PS:我正在使用 HQL,但我可以毫无问题地将 SQL 转换为 HQL。

谢谢!

我称之为 "histogram-of-histograms" 查询。它基本上是聚合之上的聚合:

select NumProjects, count(*) as NumContacts
from (select c.id, count(pc.contact_id) as NumProjects
      from contacts c left join
           project_contacts pc
           on pc.contact_id = c.id
      group by c.id
     ) c
group by NumProjects
order by NumProjects;

您可以使用 HQL 或条件查询。假设领域模型与此类似...

class Project {
    static hasMany = [contact: Contact]
}

class Contact {
    static hasMany = [project: Project]
    static belongsTo = Project
}

HQL

def count = Contact.find('SELECT COUNT(c) FROM Contact AS c WHERE size(c.project) = 0')

条件查询

def count = Contact.createCriteria().get {
    projections {
        count 'id'
    }

    sizeEq 'project', 0
}