Finding the 3 smallest numbers in a column - mysql

I have a table like this:
| songtitle | songlength |
|------------|-------------|
| 1 | 3:42 |
| 2 | 1:32 |
| 3 | 2:44 |
| 4 | 5:00 |
| 5 | 1:19 |
| 6 | 2:54 |
And I want to get the 3 shortest songs (sorted shortest to longest).
I figure I will need something like LIMIT but I'm not positive. Thanks

Sort the data and limit the number of rows you want to retreive:
select *
from your_table
order by songlength
limit 3;
If you'd like to get the 3 longest songs, simply order the data in descending order:
select *
from your_table
order by songlength desc
limit 3;
Addressing Dwza's comment, quoting from MySQL Reference Manual:
Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names, column aliases, or column positions. [...] To sort in reverse order, add the DESC (descending) keyword to the name of the column in the ORDER BY clause that you are sorting by. The default is ascending order; this can be specified explicitly using the ASC keyword.

Use the "SORT" function to sort them natively in MySQL.

Related

Sql query with mixed selected rows order

I have a table that looks like below:
| id | group_id | title |
-------------------------
| 1 | 1 | Hello |
| 2 | 1 | World |
| 3 | 2 | Foo |
| 4 | 2 | Bar |
My query may look like below to return the results above:
SELECT * FROM my_table ORDER BY id
Question
How can I order this table so that the group ids appears to be random, but still the same every time the query is executed.
Possible result example
This result looks to be in a random order. If I run the same query a week later, I want to see the exact same order which means it's not really random.
| id | group_id | title |
-------------------------
| 2 | 1 | World |
| 4 | 2 | Bar |
| 1 | 1 | Hello |
| 3 | 2 | Foo |
Appears to be random from a group_id perspective. It's no longer ordered by group_id like 1 1 2 2, but 1 2 1 2. It could also have been 2 1 1 2 or something that does not increase.
Should return the same results every time, not random each time.
I could order by title but if a title should change that row will be reordered. So the order needs to be made with the id I guess.
I want to avoid file or database caching if possible.
Is it possible?
How about taking the modulo function for your advantage.
SELECT * FROM my_table ORDER BY id % 3,id
Define a value to use with the modulo function (in my example 3) and order your table by the modulo of the id.
This should return the same order everytime you run the query and return some order that is pseudo random.
Since the modulo function can return the same value for different ids you also need to order by the original id to have a defined, reproducable order.
order this table so that the group ids appears to be random
Only ORDER BY RAND() may provide really random ordering.
but still the same every time the query is executed
Create separate static ordering table, fill it randomly with source table's ids, join it and order by it.
I did not solve the problem with the solution from #Kylro, but I found another way which works great.
SELECT * FROM my_table ORDER BY COS(id), id
Cos is sometimes a positive value and sometimes a negative value, almost random like. It works perfecty for this problem.

MySQL Selection for top x rankings

I want to make a selection in my MySQL database where I have stored numerical values in a specific column.
I have seen some websites that show 10 ten based on some criteria, and I've been wondering if it will be possible to make a selection based on numerical values.
I have my database like so:
| id | name | pts |
+----+-----------+-----+
| 1 | Brad | 3 |
| 2 | Jane | 8 |
| 3 | Jones | 10 |
| 4 | Paty | 15 |
| 5 | Sammy | 2 |
Now my question is, how do I make a query that selects only the top 3 users, based on the pts, such that it returns the result as:
1st Position = Paty => 15pts
2nd Position = Jones => 10pts
3rd Position = Jane => 8pts
?
try this :
SELECT * FROM tablename ORDER BY pts desc limit 3
Your query should use LIMIT to get the top results:
SELECT id, name, points FROM table ORDER BY pts DESC LIMIT 3
shoul do the trick.
Order by will order the table from the highest to the lowest and limit will tell mysql to get only the first three results
You can find more on this topic here for example.
And this is a question very close to your
you can use this query
SELECT CONCAT(`id` , 'Postion = ' , `name` , '=>' ,`pts` , 'pts' ) AS result FROM table ORDER BY pts DESC LIMIT 3
This Question I seen many places anyway the query is.
select top 3 * from tablename order by cols_name desc
This Query brings top 3 row with highest values based on your column.

Similar MySQL queries returning with different sorting

I've two queries which should both return thumbUrls in the same order. My goal is to use the second query, as it has to be part of another query, which won't work with the first one. I already broke down the queries, but couldn't find what's casing the difference.
Query One:
SELECT album, thumbUrl
FROM lychee_photos
WHERE album = '16'
ORDER BY takestamp ASC, id DESC LIMIT 3;
Result:
-------------------------------------------------
| album | thumbUrl |
-------------------------------------------------
| 16 | 48c4d04567590b44a0c604197a049ef5.jpeg |
| 16 | 5db0fce4937104e7d27dae64d6cd9990.jpeg |
| 16 | a70bb8499b683b1eeab17336c3f07f7e.jpeg |
-------------------------------------------------
Query Two:
SELECT album, substring_index(
GROUP_CONCAT(thumbUrl ORDER BY takestamp ASC, id DESC), ',', 3
) AS thumbs
FROM lychee_photos
WHERE album='16'
GROUP BY album;
Result:
-----------------------------------------------------------------------------------------------------------------------------
| album | thumbUrl |
-----------------------------------------------------------------------------------------------------------------------------
| 16 | 1b98e17f1af051753a958c18953adbd5.jpeg,c506f4fedb8a4df691d276d6abdb75f7.jpeg,f0cc0ba23effc0443f367ca63dd1e72f.jpeg |
-----------------------------------------------------------------------------------------------------------------------------
Expected output:
I expected to see thumbUrls in the same order as in query one.
-----------------------------------------------------------------------------------------------------------------------------
| album | thumbUrl |
-----------------------------------------------------------------------------------------------------------------------------
| 16 | 48c4d04567590b44a0c604197a049ef5.jpeg,5db0fce4937104e7d27dae64d6cd9990.jpeg,a70bb8499b683b1eeab17336c3f07f7e.jpeg |
-----------------------------------------------------------------------------------------------------------------------------
Additional details:
Data hasn't changed between the queries
Removing substring_index() doesn't affect the order
The correct thumbUrls appear in the middle of query two, when I remove substring_index()
The first query returns correctly sorted thumbUrls—the second don't. But why? How do I keep the output format of the second one and get a correct sorting?

mysql returns wrong results with random duplicate values

i need to return the best 5 scores in each category from a table.so far i have tried query below following an example from this site: selecting top n records per group
query:
select
subject_name,substring_index(substring_index
(group_concat(exams_scores.admission_no order by exams_scores.score desc),',',value),',',-1) as names,
substring_index(substring_index(group_concat(score order by score desc),',',value),',',-1)
as orderedscore
from exams_scores,students,subjects,tinyint_asc
where tinyint_asc.value >=1 and tinyint_asc.value <=5 and exam_id=2
and exams_scores.admission_no=students.admission_no and students.form_id=1 and
exams_scores.subject_code=subjects.subject_code group by exams_scores.subject_code,value;
i get the top n as i need but my problem is that its returning duplicates at random which i dont know where they are coming from
As you can see English and Math have duplicates which should not be there
+------------------+-------+--------------+
| subject_name | names | orderedscore |
+------------------+-------+--------------+
| English | 1500 | 100 |
| English | 1500 | 100 |
| English | 2491 | 100 |
| English | 1501 | 99 |
| English | 1111 | 99 |
|Mathematics | 1004 | 100 |
| Mathematics | 1004 | 100 |
| Mathematics | 2722 | 99 |
| Mathematics | 2734 | 99 |
| Mathematics | 2712 | 99 |
+-----------------------------------------+
I have checked table and no duplicates exist
to confirm there are no duplicates in the table:
select * from exams_scores
having(exam_id=2) and (subject_code=121) and (admission_no=1004);
result :
+------+--------------+---------+--------------+-------+
| id | admission_no | exam_id | subject_code | score |
+------+--------------+---------+--------------+-------+
| 4919 | 1004 | 2 | 121 | 100 |
+------+--------------+---------+--------------+-------+
1 row in set (0.00 sec)
same result for English.
If i run the query like 5 times i sometimes end up with another field having duplicate values.
can anyone tell me why my query is behaving this way..i tried adding distinct inside
group_concat(ditinct(exams_scores.admission_no))
but that didnt work ??
You're grouping by exams_scores.subject_code, value. If you add them to your selected columns (...as orderedscore, exams_scores.subject_code, value from...), you should see that all rows are distinct with respect to these two columns you grouped by. Which is the correct semantics of GROUP BY.
Edit, to clarify:
First, the SQL server removes some rows according to your WHERE clause.
Afterwards, it groups the remaining rows according to your GROUP BY clause.
Finally, it selects the colums you specified, either by directly returning a column's value or performing a GROUP_CONCAT on some of the columns and returning their accumulated value.
If you select columns not included in the GROUP BY clause, the returned results for these columns are arbitrary, since the SQL server reduces all rows equal with respect to the columns specified in the GROUP BY clause to one single row - as for the remaining columns, the results are pretty much undefined (hence the "randomness" you're experiencing), because - what should the server choose as a value for this column? It can only pick one randomly from all the reduced rows.
In fact, some SQL servers won't perform such a query and return an SQL error, since the result for those columns would be undefined, which is something you don't want to have in general. With these servers (I believe MSSQL is one of them), you more or less can only have columns in you SELECT clause which are part of your GROUP BY clause.
Edit 2: Which, finally, means that you have to refine your GROUP BY clause to obtain the grouping that you want.

Sorting words by its occurence in a database, matching similar words

I have a mysql table it has lot of words on it.
Hai.
Am i
hai
joe
This
Those
hai
In at above example "hi" is occurring three times I want to create a query which will look at this table and sort out most occurred words.
You need to use GROUP BY clause and COUNT function.
SELECT word, COUNT(*) count FROM your_table GROUP BY word ORDER BY count DESC LIMIT 0,3;
Possible output:
+------+-------+
| word | count |
+------+-------+
| hai | 2 |
| Hai. | 1 |
| This | 1 |
+------+-------+
If you want MySQL to treat hai and Hai. as the same word, you should strip all non-alpha characters before grouping. See MySQL: how to remove all non-alpha numeric characters from a string?. Then, based on method from this answer it will look like this:
SELECT LOWER(alphanum(word)) word, COUNT(*) count FROM your_table
GROUP BY LOWER(alphanum(word)) ORDER BY count DESC LIMIT 0,3;
And possible result:
+------+-------+
| word | count |
+------+-------+
| hai | 3 |
| this | 1 |
| joe | 1 |
+------+-------+
You need to compose a sql statement using the group by method that will group like things together. Something like this should get you started
select word, count(word)
from table
group by word
order by count(word) desc