【问题标题】:Select Result only if unique (sort of)仅在唯一时选择结果(有点)
【发布时间】:2021-01-29 00:35:35
【问题描述】:

我正在构建一个简单的 sql 查询,但我无法理解这个查询。 这是表格的布局:

挑战:我想从该表中获取所有内容,前提是存在阈值不为 20 的条目(按 id_order)(在这种情况下,应动态显示 ID 18)。

我在想:

SELECT * FROM `cancelorders_history` WHERE threshold != 20 GROUP BY `id_order`

虽然这会引发以下错误(并且我不确定查询是否与我正在寻找的逻辑匹配,如上所述):

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'exampletable.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

我不能使用:

SELECT * FROM `cancelorders_history` WHERE threshold != 20

因为给我的 ID 都是 13、18、19。

解决这个问题的首选方法是什么?

【问题讨论】:

    标签: mysql sql logic


    【解决方案1】:

    嗯。 . .我觉得你可以用not exists

    select coh.*
    from cancelorders_history coh
    where not exists (select 1
                      from cancelorders_history coh2
                      where coh2.id_order = coh.id_order and coh2.threshold >= 20
                     );
    

    或者,使用窗口函数:

    select coh.*
    from (select coh.*,
                 max(threshold) over (partition by id_order) as max_threshold
          from cancelorders_history coh
         ) coh
    where max_threshold < 20;
    

    【讨论】:

      【解决方案2】:

      GROUP BY 有错误,因为SELECT 的每一列都必须有一个组。代码应该是这样的:

      SELECT * FROM cancelorders_history WHERE threshold != 20 GROUP BY threshold, notification_sent, id_order, id;
      

      但是,您的查询不满足只得到一个结果的要求。看起来不想使用GROUP BY。也许ORDER BY,但你必须解释你真正想要使用的逻辑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-11
        • 2013-05-06
        • 2023-03-23
        • 1970-01-01
        • 2016-09-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多