sqlite 使用count()从2个表中选择

2eafrhcq  于 2023-10-23  发布在  SQLite
关注(0)|答案(1)|浏览(165)

Dictionary表:
| ID|名称|
| --|--|
| 1 |英语|
| 2 |意大利|
Word表格参考DictionaryID
| ID|字典ID|词|
| --|--|--|
| 1 | 1 |一|
| 2 | 1 |B|
| 3 | 2 |C|
我想用DictionaryWord表之间的左连接来实现一个查询,结果是,所有字段都来自Dictionary表,只有Word表中名为WordNumber的字段中的行数,如下所示:

public class Dictionary
{
    public long ID { get; set; }

    [Collation("NOCASE")]
    public string Name { get; set; }

    [Ignore]
    public long WordNumber { get; set; }
}

我有一个函数,它根据文本搜索返回字典列表,这是工作:

public async Task<List<Dictionary>> GetDictionariesForSearchAsync(string search)
{
    await Init();
    return await Database.Table<Dictionary>()
        .Where(w => w.Name.ToLower().Contains(search.ToLower()))
        .ToListAsync();
}

对于每个Dictionary,我读取单词的数量:

public async Task<long> GetRecordNumberForDictionary(long id)
{
    long num = await Database.Table<Word>().Where(i => i.DictionaryId == id).CountAsync();
    return num;
}

我正在重复查询(单个查询更有效)。我找不到像GroupBy这样的函数来对Word进行分组和计数。
William's code给我这个:

xuo3flqw

xuo3flqw1#

我想知道你是否尝试使用'GroupJoin'方法,该方法允许你执行左连接并根据特定的键对结果进行分组。
在本例中,您希望按“DictionaryId”对“Words”表进行分组,并计算每组的单词数。

public async Task<List<Dictionary>> GetDictionariesForSearchAsync(string search)
{
    await Init();

    var dictionaries = await (
        from dict in Database.Table<Dictionary>()
        where dict.Name.ToLower().Contains(search.ToLower())
        join wordGroup in
            (
                from word in Database.Table<Word>()
                group word by word.DictionaryId into wordGroup
                select new { DictionaryId = wordGroup.Key, WordCount = wordGroup.Count() }
            )
        on dict.ID equals wordGroup.DictionaryId into wordCounts
        from wordCount in wordCounts.DefaultIfEmpty()
        select new Dictionary
        {
            ID = dict.ID,
            Name = dict.Name,
            WordNumber = (wordCount != null) ? wordCount.WordCount : 0
        }
    ).ToListAsync();

    return dictionaries;
}

相关问题