[英]Why does this subquery result in different rows returned than the direct query?
Here's the relevant data 这是相关数据
SELECT item_group_id
,item_id
,invoice_id
FROM item
WHERE item_group_id = 92480
# Results
92480 215342 88902
92480 215343 88902
92480 215344 88902
92480 215345 88902
92480 215346 90690
92480 215347 90690
92480 215348 NULL
92480 215349 NULL
Here's the direct query 这是直接查询
SELECT MAX(item_group_id) [item_group_id]
,MAX(invoice_id) [invoice_id]
FROM item
WHERE item_group_id = 92480
GROUP BY invoice_id
# Results
92480 NULL
92480 88902
92480 90690
Here's the subquery 这是子查询
SELECT i.item_group_id
,i.invoice_id
FROM (
SELECT MAX(item_group_id) [item_group_id]
,MAX(invoice_id) [invoice_id]
FROM item
GROUP BY invoice_id
) i
WHERE i.item_group_id = 92480
# Results
92480 90690
92480 88902
I'm not sure what's going on here, I would assume that all result rows from the subquery will make up the ad-hoc table queries, but those rows with null invoice_ids are not available. 我不确定这里发生了什么,我假设子查询中的所有结果行都将组成临时表查询,但是invoice_ids为空的行不可用。
EDIT: As the selected answer below alludes to, this is a grouping problem. 编辑:由于以下所选答案暗示,这是一个分组问题。 The item
table has more item
entries in it, and with different item_group_id
s. item
表中包含更多item
条目,并且具有不同的item_group_id
。 Since item_group_id
is not grouped by, in the subquery all the items with a null invoice_id
field are grouped together. 由于未对item_group_id
进行分组,因此在子查询中,所有具有空invoice_id
字段的项目都被分组在一起。 The MAX(item_group_id)
selection then returns the highest item_group_id
, not any of a set of identical item_group_ids as in the direct query. 然后, MAX(item_group_id)
选择返回最高的item_group_id
,而不是直接查询中的一组相同的item_group_ids中的任何一个。
Changing GROUP BY invoice_id
to GROUP BY item_group_id, invoice_id
yields what I'm looking for. 将GROUP BY invoice_id
更改为GROUP BY item_group_id, invoice_id
产生我想要的内容。
The result is different because the WHERE
filter is applied at different stages of query execution in the two queries. 结果是不同的,因为WHERE
筛选器应用于两个查询中查询执行的不同阶段。
In the first query WHERE
is applied first and then the result is grouped, whereas in the second query the GROUP
ing is done first (because it is in a subquery) and the where is applied on the result of the grouping. 在第一个查询中,首先应用WHERE
,然后将结果分组,而在第二个查询中,首先进行GROUP
分组(因为它在子查询中),并将where应用于分组结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.