如何在SQLite中通过group进行外部联接?

时间:2019-02-07 04:43:16

标签: sql sqlite

我从这些类创建了三个SQLite表。我在下面的SQL中加入了这些。

public class Phrase {
    [PrimaryKey, NotNull]
    public string PhraseId { get; set; }
    public int PhraseNum { get; set; }
    public int CategoryId { get; set; }
}
public class Category {
    [PrimaryKey, NotNull]
    public int Id { get; set; }
    public int GroupId { get; set; }
    public string Name { get; set; }
    public bool Selected { get; set; }
}
public class CategoryGroup {
    [PrimaryKey, NotNull]
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsToggled { get; set; }
}

到目前为止,我有此SQL

SELECT CG.NAME, COUNT(*) AS TotalPhraseCount 
FROM Phrase AS P
JOIN Category AS C ON P.CategoryId = C.Id
JOIN CategoryGroup AS CG ON C.GroupId = CG.Id
WHERE C.Selected = 1
GROUP BY C.GroupId

哪个给了我,因为“类别”类别中的“类别”有11个短语,并且已被选中:

CategoryGroupName PhrasesCount
A                 20

但是,我需要查看每个CategoryGroup行,如果该组中未选择Category,则显示0。因此,例如,其中包括没有选择类别的CategoryGroup B:

CategoryGroupName PhrasesCount
A                 20
B                 0
C                 0

我想我可以通过外部联接来做到这一点,但是我不确定如何在SQL中实现它。

每个类别包含许多短语 每个类别组包含许多类别 每个类别仅属于一个类别组 每个短语仅属于一个类别

希望有帮助

这是我从Juan的查询中获得的输出。不知道为什么B和C行中有1

CategoryGroupName PhrasesCount
A                 20
B                 1
C                 1

2 个答案:

答案 0 :(得分:1)

使用左联接

{{1}}

答案 1 :(得分:1)

SELECT CG.NAME, COUNT(C.GroupId) AS TotalPhraseCount 
FROM       CategoryGroup AS CG
LEFT JOIN  Category AS C 
       ON  CG.Id = C.GroupId
      AND  C.Selected = 1                         
LEFT JOIN  Phrase AS P 
       ON P.CategoryId = C.Id
GROUP BY CG.NAME