Ordering by posts in another table - php

I have created a feature where users can start new topics (similar to forums).
At the moment on a page, the query for the topics are as follows:
$q = "SELECT ".TBL_COMMUNITYTHREADS.".title, ".TBL_COMMUNITYTHREADS.".id,
".TBL_COMMUNITYTHREADS.".date, ".TBL_COMMUNITYTHREADS.".author, ".TBL_USERS.".username FROM ".TBL_COMMUNITYTHREADS."
INNER JOIN ".TBL_USERS." ON ".TBL_COMMUNITYTHREADS.".author = ".TBL_USERS.".id
WHERE type = '$type'
ORDER BY date DESC LIMIT $offset, $rowsperpage ";
The tables are constants and the offset and rowsperpage are variables passed in to limit how many posts are on a page.
At the moment though, all the topics are ordered by the date.
I want them to be ordered by the latest response.
Similarly to forums, when the reponse inside the topic is newest, that topic will go to the top.
The topics are stored in tbl_communitythreads and the replies in tbl_communityreplies.
How can I ordered them by the latest repsonse.
They are linked by the threadid in tbl_communityreplies. Also in that one is the date column.
Thankyou for reading, I just cant think of how to do this.

This:
SELECT c.title, c.id, c.date, c.author, u.username,
(
SELECT MAX(reply_date)
FROM tbl_communityreplies cr
WHERE cr.thread = c.id
) AS last_reply
FROM TBL_COMMUNITYTHREADS c
JOIN TBL_USERS u
ON u.id = c.author
ORDER BY
last_reply DESC, c.id DESC
LIMIT $offset, $rowsperpage
or this:
SELECT c.title, c.id, c.date, c.author, u.username
FROM (
SELECT cr.thread, cr.reply_date, cr.id
FROM tbl_communityreplies cr
WHERE (cr.last_reply, cr.id) =
(
SELECT last_reply, id
FROM tbl_communityreplies cri
WHERE cri.thread = cr.thread
ORDER BY
thread DESC, last_reply DESC, id DESC
)
ORDER BY
last_reply DESC, id DESC
LIMIT $offset, $rowsperpage
) q
JOIN TBL_COMMUNITYTHREADS c
ON c.id = q.thread
JOIN TBL_USERS u
ON u.id = c.author
ORDER BY
q.reply_date DESC, q.id DESC
The former query is more efficient for large values of $offset, or if you have few threads with lots of replies.
Issue the following commands:
CREATE INDEX ix_communitythreads_replydate_id ON TBL_COMMUNITYTHREADS (reply_date, id)
CREATE INDEX ix_communitythreads_thread_replydate_id ON TBL_COMMUNITYTHREADS (thread, reply_date, id)
for this to work fast.

by join with another table , then you can order by column from this table.

Related

Multiple Counts in MYSQL PHP Query

I'm trying to create a leaderboard but i'm not sure how to do the mysql query.
I would like to count all the levels from a player in the skills table and get the total Level and count all the experience from a player in the experience table and get the Total Exp along with displaying the persons name from the users column.
There is 3 tables factions_mcmmo_users, factions_mcmmo_experience, factions_mcmmo_skills.
This is what i have so far but it doesn't work:
$sql = ("SELECT a.id,
(SELECT COUNT(*) FROM factions_mcmmo_experience WHERE user_id = a.id) as TotalXP,
(SELECT COUNT(*) FROM factions_mcmmo_skills WHERE user_id = a.id) as TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a LIMIT 10;");
Any help would be very appreciated
EDIT: I have it working now but i'm unsure if its the most efficient way to do things so if anyone could help me out if theres a better way, it would mean a lot.
I would also like to know if it's possible to display the total exp and level with commas if the number is in the thousands for example: total level 5,882 and total xp 582,882
EDIT 2:
I have figured out how to format the numbers but still don't know if my code is efficient
$sql = ("SELECT id, user,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_skills b WHERE b.user_id = a.id) as TotalLevel,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_experience c WHERE c.user_id = a.id) as TotalXP
FROM (SELECT id, user FROM factions_mcmmo_users) a group by id ORDER BY TotalLevel DESC, TotalXP DESC LIMIT 10;");
EDIT 3
Updated code from scaisEdge but was displaying everyones level as 1 and XP as 1, so i changed count(*) changed to sum, added an order By TotalLevel in Descending order and that seems to have worked but i can't get it to display the persons name (user column) in the user table? not sure if i was supposed to change to sum because it didn't work the other way.
$sql = ("SELECT a.id, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC
LIMIT 10;");
EDIT 4
Everything working but when i try to format the totals using "FORMAT(Sum(Columns), 0) on the inner joins, the EXP Total appears to work but the main Total Level is not displaying results that are over 1,000 and it breaks the leaderboard positioning, it should be sorting them on total level but it appears to be random, when u remove the format,0 it goes back to working
I would like it to display commas if the number number is the thousands for example: Total Level: 5,532 and Total EXP 5882,882
See live demo: http://mcbuffalo.com/playground/leaderboards/server/factions-mcmmo.php
Updated Code trying to use Format:
$sql = ("SELECT a.id, a.user, b.TotalXP, c.TotalLevel
FROM (SELECT id, user FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC;");
EDIT 5
Changed number with PHP, everything works
Original Images
you could use an couple of inner join
$sql = ("SELECT a.id, a.name, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id, name FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, COUNT(*) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, COUNT(*) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
LIMIT 10

How to get the most recent row in group in mysql?

In my mysql query, I try to get all threads with their most recent row.
$query = "SELECT th.id, tm.message, tm.date_sent, tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN thread_message tm ON th.id=tm.thread_id
JOIN (
SELECT thread_id, MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
ORDER BY tm.date_sent DESC";
This works, but the problem is, if there is two or more rows who's date is the most recent and they are the same date, then it will join with both of them. I need that third join statement to join with at most 1 row.
I also don't want to assume that the biggest id implies its the most recent row, because I could always change the dates manually later.
Does anyone know how to fix this?
Thanks
One way to do this is to establish a row number per group, in this case your group is thread_id and date_sent. With MySql, you need to use user-defined variables to do this:
SELECT th.id,
tm.message,
tm.date_sent,
tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN (
SELECT id,
thread_id,
message,
date_sent,
#rn:=IF(#prevthread_id=thread_id, #rn+1, 1) rn,
#prevthread_id:=thread_id
FROM thread_message, (SELECT #rn:=1, #prevthread_id:=0) t
ORDER BY thread_id, date_sent DESC, id
) tm ON th.id=tm.thread_id
AND tm.rn = 1
ORDER BY tm.date_sent DESC
Perhaps this is easier for you (but only because you're using mysql):
SELECT th.id,
tm.message,
tm.date_sent,
tm.date_sent>tu.last_read_date AS new
FROM thread th
JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
JOIN thread_message tm ON th.id=tm.thread_id
JOIN (
SELECT thread_id,
id,
MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id
AND q.id = tm.id
AND tm.date_sent = q.date_sent
ORDER BY tm.date_sent DESC
This will return an arbitrary id to join on.
Seems to me that if the query produces what you expect, with exception of the last JOIN you can just modify the GROUP BY which will only return one row.
JOIN (
SELECT thread_id, MAX(date_sent) date_sent
FROM thread_message
GROUP BY thread_id
) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
GROUP BY tm.date_sent
ORDER BY tm.date_sent DESC";

PHP: 2 tables - Maximum id2

I want to get all id with the max id2 value.
I tried just to get the max id2 but then it will looks for the overall maximum value of id2 inside the table , but i want to get all maxiums of id.
So I got 2 tables - table news and table topics.
Everytime I create a news there will automaticly create a topic. Now I want to show all news - and the current number of replies. So first step - topicid = id.
and every topic got id and id2.
id is the topic id
and id2 is the reply id
so if i got topic (a) with 4 comments it would look like
(id(1),id2(1))
(id(1),id2(2))
(id(1),id2(3))
(id(1),id2(4))
now a new topic (b) with 6 comments
(id(2),id2(1))
(id(2),id2(2))
(id(2),id2(3))
(id(2),id2(4))
(id(2),id2(5))
(id(2),id2(6))
so i want to get ((id(1),id2(4)) and (id(2),id2(6)))
<?php
$news = "SELECT n.titel,n.datum,n.typ_news,n.news,n.verfasser,n.time,n.topicid,
t.id, t.id2 FROM news n LEFT JOIN topics t ON t.id = n.topicid
ORDER BY n.id DESC LIMIT 10 ";
$neuenews = mysql_query($news);
while ($dnews = mysql_fetch_array($neuenews))
{
echo " <div style='text-align:center;color:#FFFFFF;font-size: 24px;'> "
.$dnews['titel'].
"a";
}
Ehm this was the solution :
$dn1 = mysql_query('select c.id, c.name, c.description, c.position,c.bild,
(select count(t.id) from topics as t where t.parent=c.id and t.id2=1) as topics,
(select count(t2.id) from topics as t2 where t2.parent=c.id and t2.id2!=1) as replies
from categories as c group by c.id order by c.position asc');
Try this:
SELECT n.titel,n.datum,n.typ_news,n.news,n.verfasser,n.time,n.topicid, t.id, MAX(t.id2) AS id2
FROM news n
LEFT JOIN
topics t
ON t.id = n.topicid
GROUP BY n.topicid
ORDER BY n.id DESC LIMIT 10
It looks like the specified/desired result from the topics table is accomplished by a query like this:
SELECT t.id
, MAX(t.id2) AS max_id2
FROM topics t
GROUP BY t.id
OPTION 1
To get that result joined to rows in news, you could use that query as an inline view in your query in place of the topics table. For example:
SELECT n.titel
, n.datum
, n.typ_news
, n.news
, n.verfasser
, n.time
, n.topicid
, t.id
, t.max_id2
FROM news n
LEFT
JOIN ( SELECT m.id
, MAX(m.id2) AS max_id2
FROM topics m
GROUP BY m.id
) t
ON t.id = n.topicid
ORDER BY n.id DESC LIMIT 10
OPTION 2
If id is UNIQUE (or PRIMARY KEY) in news table, then you may be able to eliminate the inline view, do a join to topics, and do a GROUP BY n.id, something like this:
SELECT n.titel
, n.datum
, n.typ_news
, n.news
, n.verfasser
, n.time
, n.topicid
, t.id
, MAX(t.id2) AS max_id2
FROM news n
LEFT
JOIN topics t
ON t.id = n.topicid
GROUP BY n.id
ORDER BY n.id DESC LIMIT 10
Not clear enough. what are the columns id= 1 id2=1 etc.? Two tables each with 2 columns? No clue.
I'm thinking something on the order but No clue what you actually want.
SELECT `MAX(`id2`) as MAX,`id` FROM `News` WHERE `id2` = `MAX`

Sort a MySQL result based on total count of another result

I have tables tbl_posts and tbl_comments with primary keys post_id and comment_id respectively. I tried this code:
$allPosts=mysql_query("
select c.comment_id, post_id, count(*)
from post u,
comments c
where u.comment_id = c.comment_id
group by comment_id, post_id
LIMIT 10
");
but I have no clue what it does. How do I combine two tables so that the total comments determines the order of the listed posts from tbl_posts?
Try this, it's more readable if you separate per lines and work with joins
select c.comment_id, post_id, count(*)
from post u join comments c
on u.comment_id = c.comment_id
group by comment_id, post_id LIMIT 10
It looks like you have tables named tbl_comment and tbl_post but your query has them listed as just comment and post.
select c.comment_id, post_id, count(*)
from tbl_post u, tbl_comments c
where u.comment_id = c.comment_id
group by comment_id, post_id LIMIT 10
$allPosts=mysql_query("select c.comment_id, post_id, count(*) from tbl_post u, tbl_comments c where u.comment_id = c.comment_id group by comment_id, post_id LIMIT 10");
This just fixes the query so it runs, and does not address any content issues you may have, namely the group by on both (what I am guessing) are primary keys.
** EDIT **
To fix the sorting try:
SELECT tbl_post.comment_id, count(*)
FROM tbl_post, tbl_comments
WHERE tbl_post.comment_id = tbl_comment.comment_id
GROUP BY comment_id LIMIT 10
ORDER BY count(*)
Explanation of your SQL:
You are selecting column comment_id from table comments, column post_id from table post using a inner join, grouping by comment_id, post_id, with a limit of 10 results.
I would try:
$allPosts = mysql_query("SELECT * FROM
(SELECT c.comment_id, u.post_id, COUNT(*) AS 'count' FROM post u
LEFT JOIN comments c ON c.comment_id = u.comment_id
GROUP BY c.comment_id, u.post_id)
ORDER BY count DESC LIMIT 10");

MySQL query order the results in GROUP BY 3 Tables Count

I'm coding a listing system and I'm trying to get the posts ORDER by number of comments and votes FROM 2 tables.
Table1 : Lists => id, title, detail
Table2 : Votes => voteid, listid
Table3 : Comments => commentid, listid
WHERE MY Current query is
$q = mysql_query("SELECT * FROM zoo_leads
LEFT JOIN Votes ON Lists.id=Votes.listid
LEFT JOIN Comments ON Lists.id=Comments.listid
GROUP BY Lists.id ORDER BY Comments.listid DESC LIMIT 10
it is showing me results perfectly but ORDER BY is Lists.id Instead of number of votes and comments
Try:
SELECT *
FROM zoo_leads
LEFT JOIN votes
ON lists.id = votes.listid
LEFT JOIN comments
ON lists.id = comments.listid
GROUP BY lists.id
ORDER BY COUNT(votes.id) DESC,
COUNT(comments.id) DESC
LIMIT 10
That is because you have ORDER BY Comments.listid in your SQL statement.

Categories