I have a database with nearly 100 fields.
DB structure is
id | comment | time
I need to fetch only 5 newest record (I can get those records using ORDER by time DESC). But while printing them I need to print the oldest of those 5 records first and proceed in reverse in a way that the newest record will be printed last.
SELECT s.* FROM (
SELECT id, comment, time FROM table1
ORDER BY time DESC
LIMIT 5 ) as s
ORDER BY s.time ASC
Ok, after fetching result set in ascending order with a limit of number of rows
you can do this to print them in reverse order (descending order)
$data= array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
$records = array_reverse($data);
OR
This could be done with mysql_data_seek
Directly taken from here
for ($i = mysql_num_rows($resultset) ā 1; $i >= 0; $iā) {
mysql_data_seek($resultset, $i);
$row = mysql_fetch_assoc($result);
echo $row['abc'] . ' ' . $row['xyz'] . "\n";
}
You can use PHP's array_reverse() function on your result list.
http://php.net/manual/en/function.array-reverse.php
You can use also something like this:
select * from (select * from table_name where 1=1 order by time desc
limit 5) as tbl order by tbl.time;
Edit if you have a lot of accesses to this statement it would be much better to represent it as materialized view. Though there are no materialized views in mysql it is possible to simulate them (http://lists.mysql.com/mysql/207808)
Using a materialized view or a simulated materialized view will seriously outperform the suggested php approaches. Most of the mentioned ones consume to much memory anyways .
I guess you could do something along the lines of (untested):
SELECT
*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
)
ORDER BY
time ASC
UPDATE
Apparently, the "derived table must have its own alias" (error #1248). Other answers have already done this, so I'll jump on the bandwagon. Below you'll find the revised (and tested) query:
SELECT
derived.*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
) AS derived
ORDER BY
derived.time ASC
By the way, this is supported as of MySQL 4.1.
Related
Guys am trying to select the top/recently third row, i tried this one but it doesn't work, where do i make mistake ?
<?php
$sql = "SELECT * FROM songs ORDER BY id ASC LIMIT 1,2;";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['artist'];
}
}
?>
Use OFFSET:
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The shorthand (which you are using) is reversed, so OFFSET is first then LIMIT:
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1;
Use OFFSET
Here the limit 1 It simply means and you need one record
and the offset means skip the first 2
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The parameters you use after limit should be reversed.
The first parameter is offset, and the second parameter is number of record you want.
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1
This is just my opinion--
Sorting like this should always be done in client software.
Extract the data - remove the ORDER BY for your SQL...
Sort it in your client, and select and return the third line to the caller.
You will get better scalability and maintainability than driving all of this through an SQL query.
This is my go-to approach when solving these types of problems through custom software and it has been proven out over time.
Think about this:
Select ID from songs
get the id's into your code, and sort them there. Then chose the third one in the list. Then:
select title, author, artist, ... from songs where ID = VALUE FROM ID ABOVE
Yes, you are hitting the database twice, but these are two very efficient queries and that will perform better as your database scales, than the fancy order by you propose.
In a table I am developing, you can see that there is a person with the best known time. I would like to show it in my page, and so I used this code:
$con=mysqli_connect("localhost","user","pass","database");
if( $result2 = mysqli_query($con,"SELECT playername FROM 1_toad_circuit /*name of the table*/ LIMIT 0 , 30") ) {
$row = mysqli_fetch_row($result2);
printf ("%s \n", $row[0]);
}
As output I am not getting Itoi6 (person with the best time), but I have Catfish (the first in alphabetical order). I have 3 columns as you can see on the picture (link).
I say that I am pretty new with SQL and I would like to know what do I have to fix.
You need to add an ORDER BY clause to your statement and then order by whichever field you are storing the times in.
For example, if you had a "time" field:
SELECT playername, time FROM 1_toad_circuit
ORDER BY `time` ASC
LIMIT 1
while($data=$SQL->fetch(PDO::FETCH_ASSOC)){
echo $data=['message'];
}
is that possible to reverse while loop?
I have a page echo out messages and I need put in reverse
SQL- DESC LIMIT 20
fetch last 20 messages
but my chat box is print in reverse
message 1 (oldest message)
message 2
message 3 (newest message)
You should define the order of the data set in your original SQL query.
See documentation for the ORDER BY clause.
Update
It seems that the OP wants the 20 newest messages, but ordered in reverse. Then you need to perform a subquery like this:
SELECT `message`
FROM (SELECT * FROM `table`
ORDER BY `id` DESC
LIMIT 20) AS `i`
ORDER BY `i`.`id` ASC;
After fetching records You can just reverse your returned array
http://us1.php.net/array_reverse
If you really want to reverse the data in PHP, you can use array_reverse:
// Fetch all records
$data = $SQL->fetchAll(PDO::FETCH_ASSOC);
// Reverse them
$data = array_reverse($data);
foreach ($data as $record) {
echo $record['message'];
}
Although I would recommend ordering in SQL, as it will be faster.
I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.
Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row
You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1
You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.
You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"
Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}
i have a fetch row query that returns
10 9 8 7 6 5 4 3 2 1
however, i only want to return the last value, which is "1" in this case.
i tried to do echo row[0][9] but it doesn't work.
how do i get the last value?
you can use the end() function
$row = array(10, 9, 8, 7);
echo end($row); // displays 7
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Take a look # this example. Copied from here. You should be able to achieve what you wanted by taking a look at the above example.
If you know what the column index is, you are good to go. But if you ALWAYS want the last column take a look at the mysql_num_fields function.
Try echo explode(' ', $row[0])[9]
Been a while since I've done PHP though, YMMV.
you must sort your table by DESC keyword .
I'd do it all on MySQL side, so you don't split the logic between PHP and MySQL too much (if that's applicable in this case) and use query with LIMIT 1 and ORDER BY DESC (or ASC, depending on your table).
You only want the 10th last row that was added to the table? That would be the 10th id in the list if you sort by id descending. If that's what you want, you also could tell MySQL to return exactly that row. The query gets a bit more complicated though:
SELECT t1.*
FROM table t1
INNER JOIN (
SELECT id
FROM table
ORDER BY id DESC
LIMIT 10
) t2 ON t1.id = t2.id
ORDER BY t1.id ASC
LIMIT 1
Here's my code.
$query="SELECT blog_id FROM myblogs_view where blog_id<'$id' ORDER BY blog_id DESC LIMIT 10";
$result=mysql_query($query);
while($row=mysql_fetch_row($result) or die(mysql_error())) {
echo $row;
}
This returns the values in one row. how do i access the value in the last row only?