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

SQLite:如何创建一个包含3个表和2个“端点”的内部连接?

  •  -1
  • John  · 技术社区  · 6 年前

    tbl_goal_context (many-to-many table)
    rowId(PK)  |  goalRowId(FK)  |  contextRowId (FK)  |
    1          |  2              |  5                  |
    
    tbl_context_items
    rowId(PK)  |  ...  |
    5          |  ...  |
    
    tbl_context_categories_items (many-to-many table)
    rowId(PK)  |  catRowId(FK)  |  itemRowId(FK)  |
    1          |  3             |  5              |
    

    我试图列出tbl\u context\u项中的行,这些行通过两个多对多表连接,其中catRowId和goalRowId是已知的。

    例如,假设我想从tbl\u context\u项中提取连接到的所有行 goalRowId = 2 catRowId = 3

    “错误:不明确的列名:tbl\u goal\u context.goalRowId无法执行语句”

    SELECT tbl_context_categories_items.itemRowId, tbl_context_categories_items.catRowId, tbl_goal_context.goalRowId, tbl_goal_context.contextRowId, tbl_context_items.rowId AS rowId, tbl_context_items.shortText AS shortText, tbl_context_items.userMade AS userMade
        FROM tbl_context_categories_items
        INNER JOIN tbl_goal_context ON tbl_goal_context.contextRowId = tbl_context_items.rowId
        INNER JOIN tbl_goal_context ON tbl_context_categories_items.itemRowId = tbl_context_items.rowId
        WHERE tbl_context_categories_items.catRowId = 3
            AND tbl_goal_context.goalRowId = 2
        ORDER BY tbl_context_items.shortText ASC
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   user10438974 user10438974    6 年前

    模棱两可的是你要加入 两次(两组相同的列名,以及歧义)。

    FROM tbl_context_categories_items
        INNER JOIN tbl_context_items ON tbl_context_categories_items.itemRowid = tbl_context_items.rowid
        INNER JOIN tbl_context_categories ON tbl_context_categories_items.catRowid
        INNER JOIN tbl_goal_context ON tbl_context_items.rowid = tbl_goal_context.contextRowid
        INNER JOIN tbl_goal_items ON tbl_goal_context.goalRowid = tbl_goal_items.rowid
    

    这将根据关系图连接所有表(尽管查询不需要最后一个连接,因为您不包括来自的任何列) ).