I want to do this:
Check the top 10 values of points.
Here is my condition:
If there are less than 10 records (rows) found, e.g give bonus
If the points is in top ten (among hundreds records/rows), give bonus.
So, what i do is (wrong method):
SELECT points FROM `scores` WHERE id = '1' ORDER BY score DESC LIMIT 9 , 1
That will only work if i have more then 9 (at least 10) data/records.
Is there any other way?
I am thinking of using this(not very good though):
SELECT points FROM `scores` WHERE id = '1' ORDER BY score DESC LIMIT 0 , 10
Then get the last value of mysql_fetch_assoc data. Thus, how do I get the last value of mysql_fetch_assoc data?
The previous query is close to what you want:
SELECT points FROM (
SELECT points, score
FROM scores
WHERE id = '1'
ORDER BY score DESC
LIMIT 10
) AS top_ten
ORDER BY score ASC
LIMIT 1
If you want to stick with mysql_fetch_assoc getting the last value you can utilize mysql_data_seek.
Something like this:
<?php
// ... $result is the result set from your query
$result_count = mysql_num_rows($result);
if ($result_count > 0)
{
mysql_data_seek($result, $result_count - 1);
}
$row = mysql_fetch_assoc($result);
?>
try to use this:SELECT points FROM (SELECT points FROM scores WHERE id = '1' ORDER BY score DESC LIMIT 10) ORDER BY score LIMIT 1
Related
Im looking to display rolls from a MySQLi but I would like to display one yes and one no... example
If I use this code:
$sqldisplay = $mysqli->query("SELECT `id` FROM `albums` ORDER BY `id` DESC LIMIT 5");
while ($rowdisplay = $sqldisplay->fetch_assoc()) {
echo $rowdisplay['id'].'<br>';
}
It will display
10
9
8
7
6
But im looking to display it like this:
10
8
6
4
2
Is it posible? And if so, how can it be done?
Thanks for the help! :D
To display alternating rows, first double your limit.
$sqldisplay = $mysqli->query("SELECT `id` FROM `albums` ORDER BY `id` DESC LIMIT 10");
Then use a boolean switch to determine whether each row will be displayed.
$display = true;
while ($rowdisplay = $sqldisplay->fetch_assoc()) {
if ($display) echo $rowdisplay['id'].'<br>';
$display = !$display; // switch the display on/off
}
This way, you won't have to depend on the value of the ID, something that could produce unexpected results if any IDs are missing due to deleted rows, etc. A numeric ID is a surrogate key which should have no meaning other than uniquely identifying a row.
Using WHERE (id % 2) = 0 would give you only even numbers, and using WHERE (id % 2) > 0 would get you odd numbers.
You can use this along with a subquery that selects MAX(id) and returns either 1 (for odd) or 0 (for even). This will ensure that if the id is even, just even IDs will be returned, and vice-versa, when applied with the logic explained in the paragraph above.
SELECT `id`
FROM `albums`
GROUP BY `id`
HAVING `id` % 2 = (CASE WHEN (SELECT MAX(`id`) FROM `albums`) % 2 = 0 THEN 0 ELSE 1 END)
ORDER BY `id` DESC
LIMIT 5
With Paul's comment below, it's been pointed out that you can clean up the query even more, just doing WHERE id % 2 = (SELECT MAX(id) % 2 FROM albums) instead - this way you shouldn't need any GROUP BY..HAVING.
SELECT `id`
FROM `albums`
WHERE id % 2 = (SELECT MAX(id) % 2 FROM albums)
ORDER BY `id` DESC
LIMIT 5
You can also achieve this in PHP if you wish retrieve both datasets, see Don't Panic's answer for that (although I prefer to do it in MySQL if possible).
MySQL modulus % documentation
when you set id for order by.your result is According to insert each column
you must add column in you table for this .for example you can have column orderBy and you can specify the order of each display column
and then your query same
$sqldisplay = $mysqli->query("SELECT `id` FROM `albums` ORDER BY `orderBy` DESC LIMIT 5");
Simple, just check if the modulo of the ID is 0 (no remainders) to return even numbers.
If you want to return odd numbers, change the modulo to equal 1.
If you want to select odd or even numbers depending on user input, you can easily make an if statement and use Prepared Statements to input the requested number (1 for odd ID rows to be returned, 0 for even rows).
SELECT `id` FROM `albums` WHERE `id` % 2 = 0 ORDER BY `id` DESC LIMIT 5
So your code will be:
$sqldisplay = $mysqli->query("SELECT `id` FROM `albums` WHERE `id` % 2 = 0 ORDER BY `id` DESC LIMIT 5");
while ($rowdisplay = $sqldisplay->fetch_assoc())
{
echo $rowdisplay['id'].'<br>';
}
I need help to implement how much status=1 I have in last 10 rows from results?
If its there 3 status in last 10 rows, i need to got 3 output.
SELECT * FROM results WHERE $position='$text' and make='$make' and status='1'
You need to use a subquery to get the last 10 rows, and then count how many have status = 1 in that subset.
SELECT COUNT(*) AS count
FROM (SELECT status
FROM results
WHERE $position = '$text' AND make = '$make'
ORDER BY id DESC
LIMIT 10) AS last10
WHERE status = '1'
DEMO
I extract a number of rows from my DB with a query. Let's say that the result is 120 rows. I want to order these rows by 'score'. That's easy, since every row has a field called 'score'. Next I want to order the first 20 rows of the result randomly. So: 1st order by score, then order first 20 randomly. How would I do this?
EDIT: to be clear: I want to show ALL 120 rows, just onder the first 20 of them randomly.
Thanks!
Let's suppose you've got all your results in a PHP array $rows, using something like this SQL:
SELECT * from `table_name` order by `score`;
It sounds like you know how to do that bit, so I omit the details. The bit you want is the following:
// Get the first 20 rows
$top_twenty = array_slice($rows, 0, 20)
// Order them randomly
shuffle($top_twenty);
// Put them back into the $rows array, with their new order
$rows = array_replace($rows, $top_twenty);
Have you tried shuffling the associative array obtained in the result of the SQL?
$stmt = $db->query("SELECT * FROM table ORDER BY score LIMIT 20");
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
shuffle($array);
foreach($array as $item) {
// Do something
}
SET #rowNum=0;
SELECT #rowNum:=#rowNum+1 AS rowSeq,t.*
FROM tableName t
ORDER BY case WHEN rowSeq < 20 THEN Rand() ELSE score END
Here is a SQL-only (well MySQL-only) solution:
SELECT *
FROM (SELECT *, #rn := #rn + 1 as rn
FROM table cross join
(select #rn := 0) const
ORDER BY score
) t
ORDER BY (rn <= 20) desc,
(case when rn <= 20 then rand() end),
score;
I need help on how to randomize the last 10 rows of MySql records.
$mysqld = mysql_query(select * from table where amount > amount2 and code = '$code' order by time DESC limit 1);
From the statement above I need to randomize the last 10 rows ordered by time but limited only 1 to display.
EDIT: In other words, I need to have the table ordered by time and then I need to focus on the last 10 rows. From these last 10 rows, I need to pick one and it must be random, which one I get.
Is this possible?
Thanks
Assuming that time is the time when record was inserted, this will get you the latest 10 rows from the table:
SELECT * FROM `table` WHERE `amount` > `amount2` AND `code` = '$code'
ORDER BY `time` DESC LIMIT 10
Now, you can use the result as a temporary table, sort it randomly (as it's only 10 rows) and return one row:
SELECT * FROM (
SELECT * FROM `table` WHERE `amount` > `amount2` AND `code` = '$code'
ORDER BY `time` DESC LIMIT 10
) AS temptable
ORDER BY RAND()
LIMIT 1
Try....
SELECT * FROM (SELECT * FROM yerTable ORDER BY id DESC LIMIT 10) AS tmp ORDER BY RAND() LIMIT 1
Obviously replace id with any other distinct column if preferred.
I have a mysql table. It has auto increment on the id. but I regularly delete rows so the numbers are all over the place. I need to get the last n rows out, but because of deletions, the common way of using the max of the autoincremented id column doesn't work well...
1 - Is their another way to get the bottom 50?
2 - Is their a way to get rows by actual row number? so if I have 4 rows labelled 1,2,3,4 delete row 2 then it will become 1,2,3 rather than 1,3,4?
SELECT ... ORDER BY id DESC LIMIT 50
SELECT *
FROM TABLE
ORDER BY id DESC
LIMIT 50
EDIT
To pick the last 50, but sort by id ASC
SELECT X.*
FROM ( SELECT *
FROM TABLE
ORDER BY id DESC
LIMIT 50
) X
ORDER BY X.id
1 - First get total row count like
SELECT COUNT(*) AS c FROM ...
then use
SELECT ..... LIMIT [start],[count]
2 - One idea is to use view , or procedure, but this is much more harder and may be used when there is no other way to avoid this
1 - Is their another way to get the bottom 50?
SELECT * FROM table_name ORDER BY record_id DESC LIMIT 50
2 - Is their a way to get rows by actual row number? so if I have 4 rows labelled 1,2,3,4 delete row 2 then it will become 1,2,3 rather than 1,3,4?
SELECT * FROM table_name
1 - Yes but it is ugly afaik, you do a
SELECT whateveryouwant FROM table ORDER BY yourprimarykey DESC LIMIT 50
the you fetch the rows into an array and reverse the array, in php :
$r = mysql_query('SELECT * FROM table ORDER BY primarykey DESC LIMIT 50');
$set = array();
while($row = mysql_fetch_assoc($r)) $set = $row;
$set = array_reverse($set);
foreach($set as $row) {
// display row ...
}
2 - You'll have to manage your primary key by yourself, its a bit risky ...