There is a database, a table in it, and a table in the table, everything is as usual.
The table has a time column, type Integer
You need to know the most unique value of the time field among all the rows in the table.
For example, there are 3 rows in the table, two for time is 2, and for thirds it is 3, two lines come out with time - 2 and one with time - 3, it turns out that 3 is the most unique number (least used) among all rows What SQL query can I find this number?
|
1 answer
SELECT `time`, COUNT(*) FROM `table` GROUP BY `time` ORDER BY 2 ASC LIMIT 1 - And how good is a good idea to sort by column number, and not by its name? In my opinion, it is less convenient / obvious when reading, and more prone to error when changing the query. - Regent
- How good is a good idea to sort by column number, and not by its name? IMHO preferred. For example, in this particular query it is impossible to use the field name IMHO - it does not have an alias, and using
ORDER BY 'COUNT(*)'even more dubious idea ... sorry for the usual ticks instead of backlinks - the formatting school. - Akina ORDER BY COUNT(*)I in no way suggest. It is possible that MySQL will optimize and calculateCOUNTonly once, but I don’t want to guess. But the creation of an alias forCOUNT(*)and its use inORDER BYseems to me to be the preferred option without the above disadvantages. And at the same time, I suppose, the creation of alias does not degrade the performance of the request. - RegentORDER BY `COUNT(*)`- but here you can with the opposite ones (I’m talking about formatting the code in the comments. - Regent- @Regent Well, this is probably a question of habits and preferences. Sorting by field number is familiar to me, understandable and even somewhere convenient. Besides, I don’t have cases when something is tied to the order of the fields in the result set (I consider this situation to be unacceptable), and I always add output to the end of the list of fields. - Akina
|