【问题标题】:Join two tables on specific condition在特定条件下连接两个表
【发布时间】:2019-10-05 03:10:26
【问题描述】:

我需要帮助来连接具有特定条件的两个表。我想在最近的 Table_A.Col_A 上离开加入 Table_1 和 Table_2

所以我有两张桌子

Table_1
Col_A
1
2
6 

Table_2
Col_A | Col_B
1     | p1
4     | p2
5     | p3

Result Table
Col_A | Col_B
1     | p1
2     | p1
6     | p3

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    一个相关的子查询处理这个:

    select t1.col_a,
           (select t2.col_b
            from table2 t2
            where t2.col_A <= t1.col_A
            order by t2.col_A desc
            limit 1
           )
    from table1 t1;
    

    【讨论】:

    • 现在我得到错误 Correlated scalar subqueries must be aggregated
    • @sks27 。 . .这个错误没有意义。 MySQL(以及几乎所有其他数据库)都支持这样的相关子查询。
    【解决方案2】:

    我会尝试做这样的事情。

    SELECT DISTINCT t1.col1, t2.col2
    FROM Table_1 t1 JOIN Table_2 t2 on t1.col1 <= t2.col1
    WHERE --something matches
    

    但是这篇文章的信息不多,您可以提供的详细信息越多,我们就可以更好地为您提供帮助。

    【讨论】:

      【解决方案3】:

      您可以像这样将条件放在 ON 子句中:

      select 
        t1.Col_A, t2.Col_B 
      from Table_1 t1 left join Table_2 t2
      on t2.Col_A = (select max(Col_A) from Table_2 where Col_A <= t1.Col_A)
      

      请参阅demo
      结果:

      | Col_A | Col_B |
      | ----- | ----- |
      | 1     | p1    |
      | 2     | p1    |
      | 6     | p3    |
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-16
        • 2023-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多