【问题标题】:Linking 3 tables together in MySQL在 MySQL 中将 3 个表链接在一起
【发布时间】:2013-01-05 17:12:32
【问题描述】:

我正在尝试通过一个 MySQL 请求将 3 个数据库表链接在一起。

数据库结构:

表 1:

  • table1_id(示例:1)
  • table1_name(例如:hello world)

表2:

  • table2_id(例如:空)
  • table2_name(例如:空)

表3:

  • table3_id(示例:1)
  • table3_name(例如:random_name

MySQL 请求

SELECT * FROM table1 AS a, table2 AS b, table3 AS c 
WHERE a.table1_id = b.table2_id 
 AND a.table1_id = c.table3_id AND table3_name = "random-name"

问题

上一个请求不会显示任何结果,因为table2 为空。你知道我如何从表 1 和 2 中获取数据,让table3 的字段为空而不使用两个请求吗?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您应该将请求更改为使用LEFT JOIN 而不是INNER JOIN

    select *
    from table1 t1
    left join table2 t2
      on t1.table1_id = t2.table2_id
    left join table3 t3
      on t1.table1_id = t3.table2_id
      and t3.table3_name = 'random-name'
    

    如果 id 存在于所有表中,INNER JOIN 会生成一组数据。即使table2table3 中没有记录,LEFT JOIN 也会从table1 返回记录。

    如果您在学习连接语法方面需要帮助,这里有一个很棒的visual explanation of joins

    【讨论】:

    • 完美运行!非常感谢!!
    • @JeremyWagemans 很高兴为您提供帮助,如果此答案或任何答案对您有帮助,请务必通过左侧的复选标记接受。它将帮助未来的访问者,您将因此获得网站声誉。
    【解决方案2】:

    几个想法:

    • 不要使用SELECT *,明确命名列
    • 不要使用隐式连接语法;使用ON 子句
    • 要保留在连接条件上不“匹配”的行,请使用 LEFT OUTER JOIN

    因此,试试这个:

    SELECT  a.table1_id, a.table1_name
          , b.table2_id, b.table2_name
          , c.table3_id, c.table3_name 
    FROM   table1 AS a
    LEFT OUTER JOIN table2 AS b
    ON     b.table2_id = a.table1_id
    JOIN table3 AS c
    ON     c.table3_id = a.table1_id 
    WHERE  c.table3_name = "random-name"
    

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      相关资源
      最近更新 更多