数不胜数

时间:2016-02-26 12:26:38

标签: sql grails count many-to-many hql

我在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没有问题。

谢谢!

2 个答案:

答案 0 :(得分:1)

我称之为"直方图直方图"查询。它基本上是聚合之上的聚合:

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;

答案 1 :(得分:1)

您可以使用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
}