Sorting mysql results by times from 3 tables - php

I have 3 tables: questions, articles and pictures
The rows in each table contain a current_timestamp column posted, and link to an id. I'd like to sort the results of the rows of all three by their timestamp and only echo the newest of the three (for example: if the question is newest from the ID, display that only)
if(count($interests) != 0){ foreach($interests as $interests_following){
$interestid = mysql_result(mysql_query("SELECT `id` FROM `interests` WHERE `name` = '$interests_following'"),0);
$interestquestions = #mysql_result(mysql_query("SELECT `question_text`, `posted` FROM `questions` WHERE `interest` = '$interests_following'"),0);
$interestarticles = #mysql_result(mysql_query("SELECT `article_title`, `posted` FROM `articles` WHERE `interest_id` = '$interestid'"),0);
$interestpictures = #mysql_result(mysql_query("SELECT `interest_pic_title`, `posted` FROM `interest_pictures` WHERE `interest_id` = '$interestid'"),0);
echo '.$interests_following.': //<Only display 1 newest item (article/picture/question here>

Use UNION ALL:
SELECT posted
FROM
(
SELECT `question_text`, `posted` FROM `questions`
WHERE `interest` = '$interests_following'
UNION ALL
SELECT `article_title`, `posted` FROM `articles`
WHERE `interest_id` = '$interestid'
UNION ALL
SELECT `interest_pic_title`, `posted` FROM `interest_pictures`
WHERE `interest_id` = '$interestid'
) t
ORDER BY posted DESC LIMIT 1

To get a single row back:
$sql = "SELECT * FROM WHERE `name`='$interests_following' ORDER BY `posted` DESC LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
All of the work is in the SQL
ORDER BY `posted` DESC LIMIT 1
This orders results to have the newest first, then only return the first row.
If you mean to return only one item out of the 3 tables, you have 2 choices:
Fetch a row from each and then determine the newest in PHP
Use a UNION to find the single newest row in SQL
The latter makes for less code, but will probably be less readable.

try this
$interestquestions = #mysql_result(mysql_query("SELECT `question_text`, `posted` FROM `questions` WHERE `interest` = '$interests_following' ORDER BY timestamp_field DESC limit 1"),0);
this will show only the latest data base on your timestamp.

I'll show you the SQL queries so you can see what I did; adapt it to your code as needed.
SELECT
(SELECT question_text
FROM questions ORDER BY posted DESC LIMIT 1 ),
(SELECT article_title
FROM articles ORDER BY posted DESC LIMIT 1 ),
(SELECT interest_pic_title
FROM interest_pictures ORDER BY posted DESC LIMIT 1)
;
This sorts by the timestamp DESCending, so the latest record is first, then limits it to the single record. The result will be question_text, article_title, interest_pic_title.

Related

PHP: MYSQLI Change Order By Style

Hi, i want to get data from chat table like this:
6
7
8
My Code show like this:
8
7
6
Code:
"SELECT * FROM `chat` WHERE
`chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
ORDER BY id DESC LIMIT 3"
Because you're ordering your result in descending order. You should remove the desc in ORDER BY. You can explicitly put ASC to indicate the order as ascending.
Try to read what will happens if you use DESC or ASC statements. https://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html
Hope it will help you.
use this mat and you can change the between parameters with prepared statements.comment if doesn't work.
"SELECT * FROM `chat` WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
AND (`user_1`='1' OR `user_2` = '1')
AND `id` between 6 and 10 //starting and ending offset for query so query doesn't take long time
ORDER BY id ASC LIMIT 3" // LIMIT 3 as you mentioned and ASC order
SELECT a.*
FROM
( SELECT *
FROM chat
WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
AND 1 IN(user_1,user_2)
ORDER
BY id DESC
LIMIT 3
) a
ORDER
BY id;
I have the solution of your problem - use below query:
SELECT * FROM (
SELECT * FROM `chat`
WHERE `chat-code` = 'vm1mxo3dpi9gzuo' AND
(`user_1` = '1' OR `user_2` = '1')
ORDER BY `text` DESC LIMIT 3
) t ORDER BY `text` ASC
SELECT * FROM `chat`
WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
AND (`user_1` = '1' OR `user_2` = '1')
ORDER BY id LIMIT 3 OFFSET 5
Try above query.
You can simply change your query to this (order by text ASC):
SELECT * FROM `chat`
WHERE `chat-code` = 'vm1mxo3dpi9gzuo' AND
(`user_1` = '1' OR `user_2` = '1')
ORDER BY text ASC LIMIT 3
If you still want to order by ID, simply change the DESC to ASC

How to get ORDERED and limited rows form MySQL and randomize show order

Is possible, and how to ask MySQL for
SELECT * FROM my_table ORDER by row_id DESC LIMIT 8
get the last 8, newest record from my table, with randomized order for PHP showing method
$results = $mysqli->query($query);
while($row = $results->fetch_assoc()) {
echo $row['my_col_name'];
}
Colud I, and where put the rand() in my SQL query?
Without randomize I get last 8 rows ORDERED 10,9,8,7,6,5,4,3
I want to get in the following order:
9,7,5,4,6,10,3,8;
8,7,3,6,10,9,5,4
...
You can place it inside another select:
SELECT * FROM (SELECT * FROM my_table ORDER by row_id DESC LIMIT 8) t ORDER BY RAND()
Use a subquery:
SELECT t.*
FROM (SELECT t.*
FROM my_table t
ORDER by row_id DESC
LIMIT 8
) t
ORDER BY rand();

How to order by this query?

I have table of likes/dislikes on game: id, game_id, type(like/dislike), time
Table example: Image Link
This code gives me the last week games the had likes, order by their likes count:
$limit = 10;
$time = _time() - 60*60*24*7;
$games_id = array();
$games_id_query = $this->db->execQuery("SELECT `game_id`, count(*) as `likes_count` FROM `likes` WHERE `type` = 'like' AND `time` > '{$time}' group by `game_id` order by `likes_count` DESC LIMIT {$limit}");
$games_id_num = $games_id_query->num_rows;
if($games_id_num > 0) {
while($row = $games_id_query->fetch_object()) {
unset($row->likes_count);
$games_id[] = (array) $row;
}
}
I need addition to this code. I want one more order by, and it will be the dislikes count of this game_id, ASC.
How should I do this? with SQL only... thanks very much!
You probably want something like this:
SELECT `game_id`,
SUM(IF(`type` = 'like', 1, 0)) AS likes_count,
SUM(IF(`type` = 'dislike', 1, 0)) AS dislikes_count
FROM `likes`
WHERE `time` > '{$time}'
GROUP BY `game_id`
ORDER BY `likes_count` DESC, `dislikes_count` ASC
LIMIT {$limit}
That being said, please look into using prepared statements and parameterized queries instead of directly embedding your PHP variables in your SQL.
See this question for more information: How can I prevent SQL injection in PHP?
Change from DESC to ASC, is that what you want?
SELECT game_id, count(*) as likes_count
FROM likes
WHERE type = 'like'
AND time > '{$time}'
group by game_id
order by likes_count ASC LIMIT {$limit}

mysql get max value with multiple choices

i have this poll thing, Poll A, has 3 options let's say: Option a option b option c, option a got 3 votes, option b got 2 votes option c got 3 votes,
OPTIONS VOTES
option a 3
option b 2
option c 3
and i have this mysql query which gets the options and orders by votesCount, limit 1 to get the top answer, but in my example, there are two options on top, they both have the highest values, i want a query to get those two options, n not only one, so i have to get rid of LIMIT 1
Mysql query is
$query = "SELECT `option` FROM `options` WHERE `pid` = '$pid' AND `votesCount` != '0' ORDER BY `votesCount` DESC LIMIT 1";
any suggestion?
Here is a standard way in any SQL dialect:
select p.*
from poll p
where p.votes = (select max(votes) from poll)
Thanks to #Gordon Linoff for the hint, this is how it is now
$query = "SELECT `option` FROM `options` WHERE `pid` = '$pid' AND `votesCount` = (SELECT MAX(`votesCount`) FROM `options` WHERE `pid` = '$pid' ORDER BY `votesCount` DESC LIMIT 1)";
///Just a DB function, don't mind the 0, i'm using a class
$res = $db->get_rows($db->select($query),0);
$merged = array();
foreach ($res as $r){
$merged[] = $r->option;
}
$merged = implode(',',$merged);
return $merged;

Get Latest Entry from Database

How can I get the latest entry by the latest DATE field from a MySQL database using PHP?
The rows will not be in order of date, so I can't just take the first or last row.
You want the ORDER BY clause, and perhaps the LIMIT clause.
$query = 'SELECT * FROM `table` ORDER BY `date` DESC LIMIT 1';
SELECT * FROM [Table] ORDER BY [dateColumn] DESC
If you want only the first row:
In T-SQL:
SELECT TOP(1) * FROM [Table] ORDER BY [dateColumn] DESC
In MySQL:
SELECT * FROM `Table` ORDER BY `dateColumn` DESC LIMIT 1
You don't have a unique recordid or date revised field you could key in on? I always have at least an auto incrementing numeric field in addition to data created and date revised fields. Are you sure there is nothing you can key in on?
SELECT * FROM table ORDER BY recno DESC LIMIT 1;
or
SELECT * FROM table ORDER BY date_revised DESC LIMIT 1;
So the PHP call would be:
$result = mysql_query("SELECT * FROM table ORDER BY date_revised DESC LIMIT 1");
-- Nicholas
You can use a combination of the LIMIT and ORDER BY clauses.
For example:
SELECT * FROM entries ORDER BY timestamp DESC LIMIT 1

Categories