简体   繁体   中英

Weird issue on count and group_by and maybe distinct

Scenario:

I have a table named snippets with 5 rows, I have a table named revisions with 15 rows

What I wanted to do was get all snippets, which belongs a user_id on revisions, which includes the snippet_id .

I have the following mysql query:

SELECT DISTINCT * FROM "snippets" 
INNER JOIN "revisions" 
    ON "user_id" = "1" 
    AND "snippet_id" = "snippets.id"
GROUP BY "snippets"."id" 
ORDER BY "created_at"

That should display all snippets where revisions.user_id = 1 . The problem is, why is my count different? The total results from that query is 5 , but when I do:

SELECT COUNT(distinct snippets.id) FROM "snippets" 
INNER JOIN "revisions" 
    ON "user_id" = "1" 
    AND "snippet_id" = "snippets.id"
GROUP BY "snippets"."id";

The result is 1 1 1 1 1

There is no meaning for DISTINCT COUNT(*) . May be you are looking for COUNT(DISTINCT someotherfield) instead of it. Since COUNT(*) includes any rows that has NULL values.

Update:* Don't COUNT the same field that you used in the GROUP BY clause. That is why you are getting the result 1 1 1 1 1 . In this case remove the GROUP BY "snippets"."id" clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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