【问题标题】:How to relate a table more than one time in SQL?如何在 SQL 中多次关联表?
【发布时间】:2020-03-02 11:42:42
【问题描述】:

我想关联两个表和一个关系表。表是:Person,其主键名为id_personActivity,其主键名为id_activity,以及与前两个表相关的表:Activity_Person,包含主键和外键id_activityid_person.

要使用旧的JOIN 格式关联这些表,这将起作用:

select * from activity, person, activity_person
where activity.id_activity = activity_person.id_activity and person.id_person = activity_person.id_person;

这将显示每个人参与的活动。

但现在我正在学习 JOINs,但我不知道关联出现两次的表格的正确格式是什么 (Activity_Person)。

我试过这个:

select * from 
person inner join activity_person on person.id_person = activity_person.id_person,
activity inner join activity_person on activity.id_activity = activity_person.id_activity;

但我收到以下错误:

不是唯一的表/别名:'activity_person'

正确的格式是什么?

【问题讨论】:

  • 这是一个“自联接”并使用“别名”又名“相关名称”。这是一个常见问题解答。在考虑发布之前,请始终在谷歌上搜索任何错误消息或您的问题/问题/目标的许多清晰、简洁和精确的措辞,带有和不带有您的特定字符串/名称和站点:stackoverflow.com 和标签;阅读许多答案。如果您发布问题,请使用一个短语作为标题。请参阅How to Ask 和投票箭头鼠标悬停文本。

标签: mysql sql join inner-join


【解决方案1】:

这里不需要activity_person 两次。做吧

select *
    from person
    inner join activity_person on person.id_person = activity_person.id_person
    inner join activity on activity.id_activity = activity_person.id_activity;

【讨论】:

    【解决方案2】:

    我认为你只需要两个连接:

    select *
    from person p inner join
         activity_person ap
         on p.id_person = ap.id_person inner join
         activity a
         on a.id_activity = ap.id_activity;
    

    我不确定您为什么要在查询中重复 activity_person

    另请注意,表别名使查询更易于编写和阅读。

    【讨论】:

      【解决方案3】:

      你的语法不正确。

      select * from activity, person, activity_person
      where activity.id_activity = activity_person.id_activity
            and person.id_person = activity_person.id_person;
      

      相当于:

      select *
      from person
      inner join activity_person
      on person.id_person = activity_person.id_person -- <- remove the comma there
      inner join activity
      on activity.id_activity = activity_person.id_activity;
      

      基本上,语法是这样的:

      SELECT <the fields to select>
      FROM <table name>
      JOIN <table to join>
      ON <joining condition>
      -- if you want to add another table :
      JOIN <new table to join>
      ON <joining condition>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-16
        • 2017-10-22
        • 1970-01-01
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        相关资源
        最近更新 更多