【问题标题】:JOIN 2 columns with same name but from different tables with condition from another columnJOIN 2 列具有相同名称但来自不同表的条件来自另一列
【发布时间】:2022-01-21 00:20:51
【问题描述】:

我需要从不同表中具有相同名称的 2 列中获取每个值。所有这些都具有来自另一列的匹配条件

//TABLE1
 city  | code |
here   | 123  |
there  | 567  |
another| 498  |

//TABLE2
 city  | code |
here   | 813  |
there  | 379  |
another| 111  |

“那里”城市的预期结果

| 567 |
| 379 |

我尝试了 JOIN 和 UNION 的许多可能性,但我能找到正确的方法

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我需要垂直连接表,你可以使用UNION

    SELECT code FROM table1 WHERE city = 'there'
    UNION
    SELECT code FROM table2 WHERE city = 'there'
    

    如果你有超过少量的禁忌,你需要用cahe或if从句聚合

    【讨论】:

      【解决方案2】:

      我建议你这两个请求,你可以在这个链接中看到结果: http://sqlfiddle.com/#!9/ded8d6/9

      (SELECT code FROM TABLE1 WHERE city = 'there')
      UNION
      (SELECT code FROM TABLE2 WHERE city = 'there');
      
      
      SELECT code FROM 
        (
            (SELECT * FROM TABLE1)
            UNION
            (SELECT * FROM TABLE2)
         ) T
      WHERE T.city = 'there';
      

      【讨论】:

        【解决方案3】:

        我想建议使用以下查询中的任何人,您可以在此链接中看到结果: [http://sqlfiddle.com/#!9/ded8d6/13][1]

        1.
        
            SELECT code FROM table1 WHERE city = 'there'
            UNION
            SELECT code FROM table2 WHERE city = 'there' 
        
        2. 
        
            SELECT code FROM table1 WHERE city = 'there'
            UNION ALL
            SELECT code FROM table2 WHERE city = 'there'
        

        Union 和 Union All 之间的唯一区别是 Union 提取查询中指定的行,而 Union All 提取所有行,包括两个查询中的重复项(重复值)。

        【讨论】:

          【解决方案4】:

          如果为城市设置变量,则不需要在联合查询中对其进行两次硬编码。

          set @city = 'there';
          select code
          from TABLE1
          where city = @city
          union
          select code
          from TABLE2
          where city = @city
          order by code
          
          code
          379
          567

          dbfiddle here

          上的演示

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-05-13
            • 2021-03-16
            • 1970-01-01
            • 1970-01-01
            • 2022-01-12
            • 2013-06-06
            • 1970-01-01
            • 2017-11-24
            相关资源
            最近更新 更多