2017-02-28 55 views
0

我有2个表:Claim和Type_Claim。声明在Type_Claim上有一个外部密钥。在Hibernate上,表示Claim表的Bean具有TypeClaim作为属性。Hibernate HqlL:Count和Group By包含零?

Claim 

ID TYPE 
1  2 
2  2 
3  4 
4  1 

    Type_Claim 

ID Description 
1  "Hello" 
2  "Hi" 
3  "House" 
4  "Welcome" 
5  "Bye" 

现在,我做了这个查询:

SELECT tc.description, COUNT(*) 
FROM Claim claim" 
LEFT OUTER JOIN claim.typeClaim tc 
GROUP BY tc.description "; 

我想获得此:

Description Count 
    "Hello"  1 
    "Hi"  2 
    "House"  0 
    "Welcome" 1 
    "Bye"  0 

但我得到这样的:

Description Count 
    "Hello"  1 
    "Hi"  2 
    "Welcome" 1 

如何Ç我在查询中包含0个结果?我尝试了RIGHT JOIN,但得到了同样的结果。

+0

可能复制[用mysql group显示count为0的行](http://stackoverflow.com/questions/743456/displaying-rows-with-count-0-with-mysql-group-by) – Dazak

+0

应该使用右边加入。你能发布生成的SQL吗? –

回答

1

试试这个:

SELECT tc.description, count(cl.type) 
FROM type_claim tc 
LEFT OUTER JOIN claim cl ON 
cl.type = tc.id 
GROUP BY tc.description 

它为我工作:

enter image description here

+0

是的,昨天我发现解决方案,我做了一个身份查询,但thx但是^^ – RemovedQuasar

0

聚合函数count()不会计算NULL值,因此您将得到一个零。

您必须使用LEFT JOIN代替LEFT OUTER JOIN

如果您想了解更多关于外部连接,这里是一个很好的教程:http://sqlzoo.net/wiki/Using_Null

+0

如果您仍然有疑问,请参阅:[如何在条件中显示0](http://lichao.net/eblog/how-to-display-0-in-conditional-group-by-report-in-count -sql-query-200808164.html) – Michael

+0

我已经尝试了正常的LEFT JOIN,并且得到了相同的结果。 – RemovedQuasar