Find Max Value In Database Column With Where Clause - php

Lets say I have the database table setup in this fashion,
ID | Name | Area | Timestamp
---+-------+------+------------
1 | Hill | 1 | 1293243080
2 | Sam | 1 | 1293243084
3 | Joe | 2 | 1293243087
4 | Bob | 2 | 1293243089
5 | Matt | 3 | 1293243091
6 | Billy | 3 | 1293243095
Then I wish to return the Name of the person with the largest Timestamp and with a certain Area number.
However, when I try to return for example the Name Bob I only get Billy because he has the largest Timestamp of everyone.
How can I get the php to select not only the person with the max Timestamp, but the person with a certain Area number also?
This is my code so far -
(I am looping it because I am displaying the name of the person with the largest Timestamp in each Area)
for ($t = 1; $t <= 3; $t++){
$result = mysql_query("SELECT * FROM forum_posts WHERE Area='$t' AND Timestamp=(select max(Timestamp) from forum_posts)");
while($row = mysql_fetch_array($result))
{
$post_name[$t]=$row['Name'];
}
}
print_r ($post_name);
What do you guys suggest I do?

$result = mysql_query("SELECT * FROM forum_posts WHERE Area='$t' AND Timestamp=(select max(Timestamp) from forum_posts where Area='$t')");
a better option would be.
$result = mysql_query("SELECT * FROM forum_posts WHERE Area='$t' ORDER BY Timestamp DESC LIMIT 1");

use this
$result = mysql_query("SELECT * FROM forum_posts WHERE Area='$t' ORDER BY Timestamp DESC LIMIT 1");

You need a GROUP BY on your query.

You need a OR Condition. The query would be:
$result = mysql_query("SELECT * FROM forum_posts WHERE Area='$t' OR Timestamp=(select max(Timestamp) from forum_posts)");

SELECT * FROM forum_posts (
SELECT
RANK() OVER (ORDER BY timestamp ASC) AS ranking,
name
FROM person
WHERE area = 1
) AS foo
WHERE ranking = 1

Related

How do I get distinct rows by a column?

I have a huge number of rows that I'd like to get say, last 5 records inserted in that database from 10 different users. If the same user inserted the last 3 rows into database, we must get one row, skip the others two and move to get a row per user, until it count up to 5.
A database like that:
user_id | news_id | title
1 | 1 | foo-1
2 | 2 | foo-2
3 | 3 | foo-3
1 | 4 | baa
4 | 5 | baa0
5 | 6 | baa1
5 | 7 | baa2
6 | 8 | baa3
7 | 9 | baa4
Should return:
user_id | news_id | title
1 | 1 | foo-1
2 | 2 | foo-2
3 | 3 | foo-3
4 | 5 | baa0
5 | 6 | baa1
The current filter was done by PHP, like this:
$used = array();
while ($data = mysql_fetch_array($query)) {
$uid = $data['user_id'];
if(in_array($uid, $used))
continue;
array_push($used, $uid);
// do something with data
}
But I want to refactor it, and do the filter purely by mysql, if possible. I don't know much MySql and that's why I'm having problem to archive this...
Here's what I've tried
select DISTINCT(user_id), news_id, title from XXX
WHERE GROUP BY (news_id) DESC
LIMIT 0,5
How can I do that?
1 way you can do it is to generate a partitioned row number per user and then select 5 records where RowNumber = 1.
SELECT *
FROM
(
SELECT
d.user_id
,d.news_id
,d.title
,(#rn:= if(#uid = user_id, #rn + 1,
if(#uid:=user_id,1,1)
)
) as RowNumber
FROM
Data d
CROSS JOIN (SELECT #uid:=-1, #rn:=0) vars
ORDER BY
user_id
,news_id
) t
WHERE
t.RowNumber = 1
ORDER BY news_id
LIMIT 5;
http://rextester.com/JRIZI7402 - example to show it working
Note you can change the row order by simply changing the ORDER BY statement of the derived table so if you have a column that will signify the latest record e.g. an identity column or a datetime column you can use that, but user_id must be the first criteria to be partitioned correctly.
Do it from your query.
"SELECT * FROM table GROUP BY user_id ORDER BY news_id DESC LIMIT 5"
well, i think this will achieve what you are after.
select user_id, news_id, title from tableName
GROUP BY user_id
ORDER BY news_id DESC
LIMIT 0,5
Hope this helps!

Select last two rows from mysql php

I have a database like this:
+----------+----------+------+
| username | password | time |
+----------+----------+------+
| a | b | 1234 |
| c | d | 5678 |
| e | f | 9012 |
+----------+----------+------+
Now I have to arrange this by time so I ran:
mysql_query("SELECT * FROM `table` ORDER BY `time`")
This showed me rows arranged by time in ascending order, but I have to get only username c and e or I have to get the last two rows from the query.
I have tried:
mysql_query('SELECT * FROM `table` ORDER BY `time` LIMIT 2')
But this showed me usernames a and c but I have to get the last two, how to do that?
SELECT * FROM table
ORDER BY time DESC
LIMIT 2
SELECT * FROM table ORDER BY time DESC LIMIT 2
Adding the DESC keyword will sort the results in descending order.
Try this:
SELECT * FROM table ORDER BY time DESC LIMIT 2
Try
mysqli_query('SELECT * FROM table ORDER BY time DESC LIMIT 2')
Assuming you have an id field with AUTO_INCREMENT set.
To get the last two from the table.
SELECT * FROM table
ORDER BY time DESC
LIMIT 2

Selecting users alphabetically based on a specific ID

I'm familiar with pagination, in that I can select a group of users based on a page number like so:
// setup pagination
$page = 1;
$display = 5;
$start = $display * $page - $display;
$sql = "SELECT * FROM users WHERE valid = 'Y' ORDER BY :username ASC LIMIT :start, :display";
$sth = $this->db->prepare($sql);
$sth->bindValue(':username', $username, PDO::PARAM_STR);
$sth->bindValue(':start', $start, PDO::PARAM_INT);
$sth->bindValue(':display', $display, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
What I'm trying to figure out is how to do something similar only instead of a page number I have a user id. For exmaple, given the user id "3" and a display limit of "3", I want to select that user along with the user immediately before and after alphabetically (for a total of three users). I hope that makes sense..
Any advice on how to approach this?
Here is an approach that uses three subqueries combined with union all:
(select *
from users
where valid = 'Y' and username < :username
order by username desc
limit 1
)
union all
(select *
from users
where valid = 'Y' and username = :username
order by username desc
limit 1
)
union all
(select *
from users
where valid = 'Y' and username > :username
order by username
limit 1
)
Here's one idea...
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
(SELECT * FROM ints WHERE i >= 3 ORDER BY i LIMIT 2)
UNION
(SELECT * FROM ints WHERE i < 3 ORDER BY i DESC LIMIT 1)
ORDER BY i;
+---+
| i |
+---+
| 2 |
| 3 |
| 4 |
+---+

Display MySQL results by date

I have this mysql Table:
+--------------------+---------+-------+
| date | query | count |
|--------------------+---------+-------|
|2012-11-18 09:52:00 | Michael | 1 |
|2012-11-18 10:47:10 | Tom | 2 |
|2012-11-17 15:02:12 | John | 1 |
|2012-11-17 22:52:10 | Erik | 3 |
|2012-11-16 09:42:01 | Larry | 1 |
|2012-11-16 07:41:33 | Kate | 1 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
and so on. I can simply take results and order them by date in one row via this code:
$queries = mysql_query("SELECT * FROM my_tables ORDER BY date DESC LIMIT 20");
while($row = mysql_fetch_array($queries)){
echo "Name ".$row['query']."";
}
But how to display elements from table ordered by specific date like this:
In 2012-11-18:
Michael
Tom
In 2012-11-17:
John
Erik
In 2012-11-16:
Larry
Kate
and so on. Thanks!
Here is teh PHP code:
$query = mysql_query("SELECT date, query FROM table6 ORDER BY date DESC LIMIT 20");
$group_date = null;
while ($row = mysql_fetch_assoc($query)) {
if ($group_date !== substr($row["date"], 0, 10)) {
$group_date = substr($row["date"], 0, 10);
echo "<h1>$group_date</h1>\n";
}
echo "${row['query']}<br>\n";
}
Output:
2012-11-18
Tom
Michael
2012-11-17
Erik
John
2012-11-16
Larry
Kate
Note that while this code "groups" rows by one column, it can easily be extended to group rows by multiple columns. Left as an exercise.
+1 good question, THIS QUESTION IS NOT SIMPLY HOW TO ORDER A QUERY!!
I think this can be done using GROUP_CONCAT function. this will combine the matching results when you group them and seperate them by commas. ONce you have the results you can explode or do whatever you want
http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php
Your going to have to convert and group by date, and group_concat the names. then (in php or whathaveyou) explode the names by commas, and echo the date followed by the names for each result.
edit Looks like you wanted a PHP way to solve this? oops
Use this:
SELECT * FROM my_tables WHERE date > "2012-11-16" ORDER BY date LIMIT 4
Try the WHERE statement:
select * from my_table where date_column > "2012-11-18 00:00:00" and date_column < "2012-11-18 23:59:59" order by date_column
What about
SELECT * FROM my_tables GROUP BY YEAR(date), MONTH(date), DAY(date) ORDER BY date DESC LIMIT 20

Mysql SELECT different

I have a question.
My database table is something like this:
| ID | Name | Value | param |
| 1 | Michael | 290 | X |
| 2 | John | 300 | X |
| 3 | Michael | 270 | X |
| 4 | John | 280 | X |
| 5 | Michael | 256 | Y |
| 6 | Michael | 230 | Y |
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
So, I want to use a form to select the latest rows with different param but equal name.
For example, if I search for "Michael", I want to use PHP to show the latest value for the param X and the latest value for the param Y (returning 2 rows).
Michael: Param Y: 230
Michael: Param X: 270
And if I search for "John" I get:
John: Param X: 280.
The code
$sql = "SELECT * FROM thetable WHERE name = 'Michael' ORDER BY ID DESC";
$result = mysql_query($sql);
Now I just want for it to select only the latest rows with different param.
Thanks in advance.
Are the approaches listed won't work with n variable "params". I think something similar may work:
SELECT
t.*
FROM Table1 t
JOIN
(SELECT
max(id) AS maxid
FROM Table1
GROUP BY name,param) x
on x.maxid = t.id
WHERE name='Michael'
See http://sqlfiddle.com/#!2/64dc4/11
Use UNION
SELECT * From table WHERE name='Michael' AND PARAM='X' ORDER BY ID DESC LIMIT 1
UNION
SELECT * From table WHERE name='Michael' AND PARAM='Y' ORDER BY ID DESC LIMIT 1
use LIMIT if you want to select just one row ( hope i understood the question )
$sql = "SELECT * FROM thetable WHERE name = 'Michael' AND param = 'x' ORDER BY Value DESC LIMIT 1
UNION
SELECT * FROM thetable WHERE name = 'Michael' AND param = 'y' ORDER BY Value DESC LIMIT 1"

Categories