Using the JOIN function
I'm new to MySQL and am trying to learn more about the JOIN function.
Let's say I have the following code and I want to find the count for each level of the variable and then join the two column. So the data looks like:
in_clicks:
one
one
one
two
three
four
four
four
four
four
five
five
six
seven
seven
seven
eight
and I'm trying to generate the following output:
four 5
one 3
seven 3
five 2
two 1
three 1
six 1
eight 1
Not knowing anything about the JOIN function, I can use something similar to the fo开发者_如何学Pythonllowing code to get my desired result. (it doesn't work)
SELECT(SELECT * FROM in_clicks) AS keys,
(SELECT COUNT(*) FROM in_clicks) AS KeysNum;
However, how can I use the JOIN function to optimize my sql code?
You don't need a join here at all. Assuming that number
is the column you have listed:
SELECT number, COUNT(number)
FROM in_clicks
GROUP BY number
ORDER BY COUNT(number) DESC
The COUNT()
aggregate function basically counts the number of rows. (COUNT(*)
would have worked just as well.) The magic here is GROUP BY number
, which instructs the database to group the results by distinct values of number
; the aggregate functions will evaluate each group separately. Since there are five rows in the "four" group, COUNT()
over that group will yield 5.
Selecting the number
column is possible because we have grouped by it; without GROUP BY number
we could not* select number
alongside of an aggregate, since that wouldn't make sense. Selecting this column allows you to see which group the corresponding aggregate result belongs to.
And the ORDER BY
clause should be self-explanatory... sort the results descending by the count of rows in that group. Note that the order of rows whose counts are the same is unspecified; you can do ORDER BY COUNT(number) DESC, number ASC
if you want to order first by the count descending, then the number
column ascending... but note that it will be a text comparison, so the order would be four, one, seven, five, eight, six, three, two. If you order only by the count then the relative order of the one/seven and two/three/six/eight rows will not be reliable, since they have equal counts.
* Actually it is possible in MySQL to select non-aggregated columns that are not included in GROUP BY, but this is non-standard and should be used with utmost caution. Read more about it here.
精彩评论