【问题标题】:SELECT rows having same value in two fields, and different value in anotherSELECT 行在两个字段中具有相同的值,而在另一个字段中具有不同的值
【发布时间】:2021-05-18 02:04:39
【问题描述】:

我想选择在column1column2 中具有相同值但在column3 中不同的行。

这是我的桌子。

column1 column2 column3
a J abc
a K def
a L xyz
b J abc
b J def
b L xyz
c K def
c K def

这是我想要的输出。

column1 column2
b J

这是我尝试过的。

SELECT column1, column2
FROM my_table
GROUP BY column1, column2, column3
HAVING COUNT(column1) > 1;

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我想选择在 column1 和 column2 中具有相同值但在 column3 中具有不同值的行。

    使用exists:

    select t.*
    from my_table t
    where exists (select 1
                  from my_table t2
                  where t2.column1 = t.column1 and t2.column2 = t.column2 and
                        t2.column3 <> t.column3
                 );
    

    不过,您的示例结果表明您只需要 column1/column2 对。如果是这样:

    SELECT column1, column2
    FROM my_table
    GROUP BY column1, column2
    HAVING MIN(column3) <> MAX(column3);
    

    您的查询版本只返回 column1/column2 对,其中 column3 值超过一行。

    【讨论】:

      【解决方案2】:

      我认为应该这样做,对您的版本进行小修正:

      SELECT column1, column2
      FROM my_table
      GROUP BY column1, column2
      HAVING COUNT(DISTINCT column3) > 1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-18
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多