简体   繁体   English

MySQL-为什么将近2个相同的查询导致2个不同的结果? 通过...分组

[英]MySQL - Why would nearly 2 identical queries result in 2 different results? GROUP BY

I have 2 queries that are nearly identical, one with a GROUP BY, one without. 我有2个几乎相同的查询,一个带有GROUP BY,一个没有。 The results are very different. 结果非常不同。 The GROUP BY query results in over double the non-GROUP BY query result. GROUP BY查询结果是非GROUP BY查询结果的两倍多。

Query 1: 查询1:

SELECT table2.name, COUNT(DISTINCT(op.id))
FROM op INNER JOIN table1 ON table1.EID = op.ID
    INNER JOIN table3 ON table3.id = table1.jobid
    INNER JOIN table2 ON table2.id = table3.CatID
WHERE op.BID = 1
    AND op.ActiveStartDate <= NOW()
    AND op.ActiveEndDate >= NOW()
GROUP BY table2.name
ORDER BY COUNT(*) DESC;

Query 2: 查询2:

SELECT op.Type, COUNT(DISTINCT op.id)
FROM op
WHERE op.BID = 1
AND op.ActiveStartDate <= NOW()
    AND op.ActiveEndDate >= NOW()
ORDER BY op.Type ASC;

These should result in the same result. 这些将导致相同的结果。 When playing around with them, once I remove the "GROUP BY" from query 1, the result is the same. 与他们一起玩耍时,一旦我从查询1中删除了“ GROUP BY”,结果是相同的。 If I put the "GROUP BY" back into Query 1, the result is more than doubled. 如果将“ GROUP BY”放回查询1,结果将增加一倍以上。

Edit: It seems the additional INNER JOINS are not affecting the results, but rather the GROUP BY in query 1. If I remove the GROUP BY in query 1, the results between the 2 queries are identical. 编辑:似乎其他内部联接不会影响结果,而是查询1中的GROUP BY。如果我删除查询1中的GROUP BY,则两个查询之间的结果相同。 If I add the GROUP BY back into query 1, the results are very different. 如果我将GROUP BY重新添加到查询1中,则结果会大不相同。

I don't know how you think that those are nearly identical queries; 我不知道您如何看待那些几乎相同的查询; they are very different. 他们是非常不同的。 Anyway, you shouldn't remove the GROUP BY from the first one, but add a GROUP BY on the second query: 无论如何,您不应从第一个查询中删除GROUP BY ,而应在第二个查询中添加GROUP BY

SELECT op.Type, COUNT(DISTINCT op.id)
FROM op
WHERE op.BID = 1
AND op.ActiveStartDate <= NOW()
    AND op.ActiveEndDate >= NOW()
GROUP BY op.Type
ORDER BY op.Type ASC;

Of course, this doesn't mean that you'll get the same results anyway, since the first query has 3 extra joins. 当然,这并不意味着您将获得相同的结果,因为第一个查询具有3个额外的联接。

the queries are not at all "nearly identical..." in my view. 在我看来,查询根本不是“几乎完全相同...”。 you have INNER JOIN with other tabls that can have duplicates and so the INNER JOIN will increase the number of rows by that number. 您拥有INNER JOIN以及其他具有重复项的表,因此INNER JOIN将使该行数增加。 you can check the explaination in here 你可以在这里查看解释

INNER JOIN and GROUP BY 内部加入和分组依据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM