Chris
Chris

Reputation: 4364

SQL query with different results

SELECT postID, threadID, COUNT(DISTINCT postID) as count
FROM wbb1_1_post post
LEFT JOIN wcf1_user_to_groups groups
ON post.userID = groups.userID
WHERE threadID IN (468)
AND groupID IN (4,10)
AND isDisabled != 1
AND isDeleted != 1
ORDER BY postID ASC

Chris = groupID 4

Sebastian S. = groupID 10

Result:

 postID  threadID  count 
  2811     468      2

Everything is correct.

enter image description here

SELECT postID, threadID, COUNT(DISTINCT postID) as count
FROM wbb1_1_post post
LEFT JOIN wcf1_user_to_groups groups
ON post.userID = groups.userID
WHERE threadID IN (68)
AND groupID IN (7)
AND isDisabled != 1
AND isDeleted != 1
ORDER BY postID ASC

talishh and Bender = groupID 7

Result:

postID  threadID    count
349 (wrong!) 68        3

The result should be 308, cause I want the oldest post (that's why I ORDER by postID ASC). enter image description here Is there a way to optimize this query?

Upvotes: 0

Views: 68

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

It's because mysql it's really generous with aggregate functions (COUNT, MIN...) and grouping. The bad part : you ain't got control about how it groups... And ORDER BY doesn't seem to correct the problem in your case.

Other DBMS (and ANSI SQL) force you to group the fields which aren't in aggregate functions, when you use one. Looks boring, but "you know what you get".

In your case, simply use the MIN on PostID and GROUP BY threadID should do the trick.

SELECT MIN(postID), threadID, COUNT(*) as count
FROM wbb1_1_post post
LEFT JOIN wcf1_user_to_groups groups
ON post.userID = groups.userID
WHERE threadID IN (68)
AND groupID IN (7)
AND isDisabled != 1
AND isDeleted != 1
group by threadID

by the way, your LEFT JOIN doesn't make sense (if I'm not wrong) as you use your joined entity in a where statement.

And no need to use IN if you put only one value, but I guess this is just sample code.

And no need to use COUNT(distinct postID) with a correct grouping. Just use COUNT(*)

Upvotes: 1

Related Questions