Select 只有唯一(某种程度上)的结果
Select Result only if unique (sort of)
我正在构建一个简单的 sql 查询,但我无法理解这个问题。
这是 table:
的布局
挑战:我想从这个 table 中获取所有内容,前提是有一个条目(id_order)没有阈值 20(在这种情况下,只有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。
解决这个问题的首选方法是什么?
嗯。 . .我想你可以使用 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
);
或者,使用 window 函数:
select coh.*
from (select coh.*,
max(threshold) over (partition by id_order) as max_threshold
from cancelorders_history coh
) coh
where max_threshold < 20;
您在 GROUP BY
上有一个错误,因为您 SELECT
的每一列都必须有一个组。代码应该是这样的:
SELECT * FROM cancelorders_history WHERE threshold != 20 GROUP BY threshold, notification_sent, id_order, id;
但是,您的查询不符合只能获得一个结果的要求。看起来不想使用 GROUP BY
。也许 ORDER BY
,但你必须解释你真正想要使用的逻辑。
我正在构建一个简单的 sql 查询,但我无法理解这个问题。 这是 table:
的布局挑战:我想从这个 table 中获取所有内容,前提是有一个条目(id_order)没有阈值 20(在这种情况下,只有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。
解决这个问题的首选方法是什么?
嗯。 . .我想你可以使用 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
);
或者,使用 window 函数:
select coh.*
from (select coh.*,
max(threshold) over (partition by id_order) as max_threshold
from cancelorders_history coh
) coh
where max_threshold < 20;
您在 GROUP BY
上有一个错误,因为您 SELECT
的每一列都必须有一个组。代码应该是这样的:
SELECT * FROM cancelorders_history WHERE threshold != 20 GROUP BY threshold, notification_sent, id_order, id;
但是,您的查询不符合只能获得一个结果的要求。看起来不想使用 GROUP BY
。也许 ORDER BY
,但你必须解释你真正想要使用的逻辑。