代码之家  ›  专栏  ›  技术社区  ›  CodeFusionMobile

是否统计SQLite数据库查询中的关联?

  •  1
  • CodeFusionMobile  · 技术社区  · 14 年前

    我有一个sqlite数据库,其中有三个表:notes、list和notes in list。

    注释和列表都有一个自动生成的ID列和一些额外的数据列,如标题。列表中的注释是一个带有自动键的关联表,以及指向注释ID和列表ID的两个外键。

    我有一个返回给定列表中所有注释的查询:

    Select _id, title From Notes
    Join Notes_in_Lists On Notes._id=Notes_in_Lists.note_id
    Where Notes_in_Lists.list_id=2
    

    例如,这将返回列表2中的所有注释标题和ID。

    但是,注释可以在多个列表中,我需要知道注释是否与多个列表关联。这由“列表”中的相同注释\u表示。注释\u id在“列表”表中的注释\u中列出多次。

    简单到可以自己做:

    Select Count(note_id) From Notes_in_Lists Where note_id=2
    

    但是我需要将上面的两个查询组合成一个查询,我不知道从哪里开始。

    编辑
    样本数据

    Notes:  
    _id title  
    1   "Note 1"
    2   "Note 2" 
    3   "Note 3"   
    4   "Note 4" 
    
    Note_in_Lists
    _id note_id list_id  
    1   1       2  
    2   1       3  
    3   2       2  
    4   3       1   
    5   4       2  
    6   4       4
    7   4       5  
    

    示例输出(查询列表2的内容):

    _id  title      numberOfLists
    1    "Note 1"   2
    2    "Note 2"   1
    4    "Note 4"   3
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   MPelletier    14 年前
    Select Notes._id, Notes.title, Count(Nil2.list_id)
    From Notes
    Inner Join Notes_in_Lists NiL1 On Notes._id=NiL1.note_id
    Inner Join Notes_in_Lists NiL2 On Notes._id=NiL2.note_id
    Where NiL1.list_id=2
    Group By Notes._id, Notes.title;
    

    做两个连接看起来很浪费,但这基本上是运行两个查询所需要的。

        2
  •  0
  •   Michael Pakhantsov    14 年前
    SELECT n._ID, Title, Count(*) numberOfLists
    FROM Notes n, Notes_In_Lists l
    where n._id = l.note_id
      AND NOT EXISTS (Select 1 
                  from notes_in_lists l2 where 
                  l2.note_Id = n._id
                  AND l._Id = 2)
    group by n._ID, n.Title