【问题标题】:SQL join data from two tables with multiple data from one tableSQL将两个表中的数据与一个表中的多个数据连接起来
【发布时间】:2014-08-18 01:40:11
【问题描述】:

我有两张桌子,第一张是这样设置的:

name(PK), height, width, age

第二张表是这样设置的:

name1, name2

我将如何将两个表相互连接以通过以下方式输出数据:

name1, name2, height1, height2, width1, width2, age1, age2

第一个表中的名称可以连接到第二个表中的名称。

【问题讨论】:

  • 那么,一张表和第二张表的 PK(name) 有什么关系?请显示示例数据。

标签: sql join


【解决方案1】:

您可以使用不同的别名将 table1(每行包含名称、高度、宽度、年龄值)两次放入查询中。我敢肯定,如果 table2 (t2) 中的 name1 或 name2 值在 table1 (t11 和 t12) 中不存在,那么性能分析将是为了以及可能对两个 table1 引用(t11 和 t12) 进行外部连接。

SELECT
  t2.name1, 
  t2.name2, 
  t11.height height1, 
  t12.height height2, 
  t11.width width1,
  t12.width width2,
  t11.age age1,
  t12.age age2
FROM
  table2 t2,  -- contains rows with name1, name2
  table1 t11, -- contains rows with name, height, width, age
  table1 t12  -- contains same rows as t11 with name, height, width, age
WHERE t12.name = t2.name2 
  AND t11.name = t2.name1

【讨论】:

    【解决方案2】:

    这是对我有用的查询。

    SELECT 
    table2.name1, table2.name2,
    t1.height as 'name1_height',
    t2.height as 'name2_height',
    FROM table2
    INNER JOIN table1 t1 on (table1.name1 = t1.name)
    INNER JOIN table1 t2 on (table1.name2 = t2.name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2015-08-18
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      相关资源
      最近更新 更多