【问题标题】:query using joins使用连接查询
【发布时间】:2021-05-22 17:42:32
【问题描述】:

我有两张桌子

table_1

number type name
12 1 steve
12 2 smith
12 2 jack

等等……

类似

table_2

number type name
12 1 abraham
12 2 jack
12 2 smith

这里我正在做内部连接,当数字和类型相等时,我需要输出名称不匹配的地方。我的查询是

select * from table1,table2 
where table1.number=table2.number and table1.type=table2.type and table1.name <> table2.name 

预期输出:

number type name
12 1 abraham

而不是来自类型'2'

但输出显示类型为“2”的 smith jack 和 jack smith,因为在两个表中都有名为 jack,smith 的数据为类型 2。预期的输出仅适用于类型“1”,因为有mismatch 谁能帮帮我?

【问题讨论】:

    标签: mysql sql join left-join inner-join


    【解决方案1】:

    嗯。 . .你可以使用not exists:

    select t1.*
    from table1 t1 
    where not exists (select 1
                      from table2 t2
                      where t2.number = t1.number and t2.type = t1.type
                     );
     
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用子查询来比较 table_1 和 table_2 之间的数据。但是,我不确定您的表格大小和这些表格中的索引。使用此查询时请小心,因为它是一个昂贵的查询。

      SELECT t1.*
      FROM table_1 t1
      WHERE (t1.number, t1.type, t1.name) NOT IN (
        SELECT t2.number, t2.type, t2.name
        FROM table_2 t2
      );
      

      【讨论】:

        【解决方案3】:

        这是一个奇怪的情况。 Gordon's 可能更好,但这里有一个替代解决方案:

        Fiddle

        select * from table2
        where CONCAT( cast(number as char), cast(type as char), name) NOT IN
         (SELECT CONCAT( cast(number as char), cast(type as char), name) from table1)
        

        【讨论】:

        • 看到这种事情我的心都沉了:-(
        • 我也是,@Strawberry,我也是。选择上面的 WHERE NOT EXISTS。
        猜你喜欢
        • 2010-10-27
        • 1970-01-01
        • 1970-01-01
        • 2010-12-28
        • 2019-01-27
        • 1970-01-01
        • 2011-07-20
        • 2021-08-30
        • 1970-01-01
        相关资源
        最近更新 更多