I'm trying to figure out how to do this on my own but it looks like a dead end to me.
I am working under wordpress framework and with some custom tables.
The result i am trying to achieve is very simple but the way to get there is just too much for my head right now.
I need to select the top 50 results from tableOne based on the ammount of times that the id from tableOne is mentioned in tableTwo under some simple where conditions.
Using $wpdb class for the latest WordPress build, what can i use to achieve this?
Thanks
This is the Simple tableOne Query to get all posts:
$allPosts = $wpdb->get_results("SELECT * FROM pokeGrid_images WHERE status='0' ORDER BY tempo DESC LIMIT ".$limit." OFFSET ".$offset."");
Now i need the first 50 results from this table, based on the number of times their id is mentioned on the second table with this structure: http://prntscr.com/byz2qw
Edit:
http://prntscr.com/byz79b
Note: Basically this is a forum, table one has the posts, table 2 the upvotes.
The expression must gather the most upvoted posts for the last X days.
If it was 1 post the expression would be Select Count(*) FROM tableTwo Where tempo > then ".$variableWithUnixTimeDIff."
column tempo is a now() timestamp.
Thanks
Note: Basically this is a forum, table one has the posts, table 2 the
upvotes. The expression must gather the most upvoted posts for the
last X days. If it was 1 post the expression would be Select Count(*)
FROM tableTwo Where tempo > then ".$variableWithUnixTimeDIff."
SELECT *, Sum(score) AS totalScore FROM tableTwo INNER JOIN tableOne ON tableTwo.memeID = tableOne.id GROUP BY memeID ORDER BY totalScore DESC;
Try this query.
//Edit - I just created a sample table with my own data. I only created the tableTwo, where this query did work:
SELECT *, Sum(score) AS totalScore FROM tableTwo GROUP BY memeID ORDER BY totalScore DESC
So after that, just inner join data from tableOne and it will work!
Related
I’m really struggling with how to write a query which randomly selects 50 DISTINCT random titles from one table in my MySQL database and then selects 1 random excerpt from each title from a separate table. The first table is titles and the second is excerpts.
I’ve tried two queries nested together but this either doesn’t work or returns duplicate titles despite supposedly being DISTINCT.
Could somebody please, PLEASE help me with where I’m going wrong?!
My existing PHP:
$distincttitlequery = “SELECT DISTINCT titleid FROM titles ORDER BY rand() LIMIT 50”;
$distincttitleresult = mysql_query($cxn,$distincttitlequery);
while ($distinctqueryreturn = mysqli_fetch_assoc($distincttitlequery))
{
extract ($distinctqueryreturn);
$selectedtitle = $titleid;
$randomexcerptquery = “SELECT excerpts.titleid, excerpts.excerptid, excerpts.excerptsynopsis, title.titleid, title.title FROM excerpts INNER JOIN titles ON excerpts.titleid=title.titleid WHERE titleid = ‘$selectedtitle’ ORDER BY rand() LIMIT 1”;
$randomexcerptresults = mysql_query($cxn,$randomexcerptquery);
while ($randomexcerptreturn = mysqli_fetch_assoc($randomexcerptquery))
{
[ECHO RESULTS HERE]
}};
I’ve read in similar posts about GROUP BY but I need to create a query which deals with distinct, random and joined tables and I have absolutely no idea where to start!
My existing code uses DISTINCT on multiple columns and joins the tables but this leads to titles being repeated in returned results. I can LIVE with that but I’d love to perfect it!
Thank you in advance for your help with this.
In mysql 8 you can use row_number to get 1 random row per titleid
SELECT
titleid,title,excerptid,excerptsynopsis
FROM (
SELECT
e.titleid, e.excerptid, e.excerptsynopsis
,ROW_NUMBER() OVER( PARTITION BY e.titleid ORDER BY rand()) rn
, t.title
FROM excerpts e
INNER JOIN (SELECT DISTINCT titleid FROM titles ORDER BY rand() LIMIT 50) t ON e.titleid=t.titleid
) t1
WHERE rn = 1
First I am new to SQL and PHP.
I have created a simple social networking web app so users can post and follow others to see new posts from them.
At home page a user can first see posts from all users he is followong.
but what i want is to make the user see some other random popular posts that will be ordered by Likes.
here what i have done to get posts from users i follow:
SELECT * FROM posts WHERE author_id in
(SELECT followedID FROM follows WHERE
followerID=:myID)
ORDER BY id DESC LIMIT 10
Now let's say you are following only 1 person. and that person has only one post. here you will see no more than a post!
That's why i want to show more posts when a user has already seen all posts.
i want some easy way to get other posts when the above query has done getting some specific posts.
This is the next query i'd like to execute.
SELECT * FROM posts ORDER BY post_likes DESC LIMIT 10
I wouldn't recommend union, because it incurs overhead for removing duplicates.
Instead, you can use a LEFT JOIN:
SELECT p.*
FROM posts p LEFT JOIN
follows f
ON p.author_id = f.follows_id AND
f.followerID = :myID
ORDER BY (f.follows_id IS NOT NULL) DESC,
(CASE WHEN f.follows_id IS NOT NULL THEN p.id END),
p.post_likes DESC
LIMIT 10;
The ORDER BY puts the followed posts first. The other two clauses order each of the groups by the criteria you want.
You may use UNION to do what you want
(SELECT * FROM posts WHERE author_id in
(SELECT followedID FROM follows WHERE
followerID=:myID)
ORDER BY id DESC limit 0,10)
union
(SELECT * FROM posts ORDER BY post_likes DESC limit 0,10)
LIMIT 0, 10
UNION will automatically append the 2nd query result to the 1st query result, and then show only the number of records specified by the LIMIT clause
Please note that union works only if the queries are of the same structure (which in this case is positive)
Please note that the use of parenthesis is mandatory if you use order by or limit or both
I have used 3 limit clauses (one for each query , and one for the final result of union) AND Both queries have ORDER BY clause. This is to make sure that the records extracted are what you want. (to show the followed posts first, and both are ordered properly)
I'm building my own tag system for a forum I'm making. Everything is working perfectly, but I am trying to echo a list of the most popular tags but I can't find which query to use..
My tables look like this:
I need a list of the 20 most popular tags, so the tag_names of which the tag_id appear the most in the article_tag_xref table. Anyone who has an idea what the query should look like? Thanks!
You can use the following query:
SELECT t.tag_id, t.tag_name, COUNT(article_id) AS cnt
FROM Article_Tag_Xref AS a
INNER JOIN Tag AS t ON a.tag_id = t.tag_id
GROUP BY t.tag_id, t.tag_name
ORDER BY COUNT(article_id) DESC LIMIT 20
COUNT(article_id) returns the number of appearances of each tag_ig in the Article_Tag_Xref table. Thus, order by this count in descending order and applying a LIMIT 20 returns the 20 most popular tag_ig values.
The following should work out for you, as you only asked about the tag_names without their count.
SELECT tag_name
FROM Tag
WHERE tag_id IN ( SELECT tag_id, COUNT(article_id)
FROM Article_Tag_Xref
GROUP BY tag_id
ORDER BY COUNT(article_id) DESC
LIMIT 20)
The subquery returns the top 20 tag_ids and their count.
I'm putting together a simple forum script with topics/posts. I'm trying to order topics by latest post and I've had some luck with the answer in the following question: MYSQL Order from another Table, but the problem I have is that some topics don't have any posts yet, so the query doesn't select those topics at all.
Current coding is:
SELECT DISTINCT forum.*
FROM forum
INNER JOIN forum_posts
ON forum.id = forum_posts.parent_id
GROUP BY forum.id
ORDER BY forum_posts.parent_id DESC,
forum_posts.time_created DESC
LIMIT ?,?
I want to tell the ORDER BY to order by forum.time_created if there are no matches in forum_posts.parent_id for a topic.
On a side note, I would also like to know how to put a WHERE clause into this query as well. I want to only get rows from forum table "WHERE access <= ?", but can't work out where to put that snippet in.
Any help much appreciated!
EDIT:
Target is to return topics (from forum table)
According to following details:
WHERE forum.access <= ?
LIMIT ?,?
ORDER BY
Latest Post From forum_posts table with forum_posts.parent_id matching on forum.id,
or forum.time_created
EDIT 2:
An example SQLfiddle with relevant data. This doesn't work as the order should really come out as 11,10,9,1,2
http://sqlfiddle.com/#!2/83535/2
Have a look at this: http://sqlfiddle.com/#!2/be909/1
Here's my final query:
SELECT forum.*, recent_forum_posts.time_created as latest_post
FROM forum
LEFT JOIN (SELECT MAX(forum_posts.time_created) as time_created, forum_posts.parent_id
FROM forum_posts
GROUP BY forum_posts.parent_id) AS recent_forum_posts
ON forum.id = recent_forum_posts.parent_id
WHERE forum.access > 2
ORDER BY recent_forum_posts.time_created IS NULL DESC,
recent_forum_posts.time_created DESC,
forum.time_created DESC
LIMIT 5
Essentially, the subquery (the bit in brackets after LEFT JOIN) selects the most recent post for each parent_id from the forum_posts table.
That is then LEFT JOINed (as we want to list all forum's even if there are no posts yet).
I have the following results for my database table:
The Query:
SELECT
service_titles.user_id, service_titles.slide_id, service_titles.name as title_name ,service_names.name as service_name
FROM service_names
INNER JOIN service_titles ON service_names.title_id = service_titles.id
So what needs to happen is:
If the user has 2 unique service titles, then the max number of service_names for that title will be 6
If the user has 1 service title, the the max number of service_names for that title will be 16
I will be using PHP for all of the coding, but I am wondering how I would go about this. I need a way to count how many unique service_titles there are for that user and slide, and then count how many service items there are for each title.
Thanks for any help!
SELECT COUNT(DISTINCT service_titles.name)
FROM service_names
INNER JOIN service_titles ON service_names.title_id = service_titles.id
GROUP BY service_titles.user_id, service_titles.slide_id
That'll get you the number of distinct title_names for each user_id/slide_id combo.
SELECT COUNT(DISTINCT service_names.name)
FROM service_names
INNER JOIN service_titles ON service_names.title_id = service_titles.id
GROUP BY service_titles.user_id, service_titles.slide_id
... and that's the number of distinct service_names for same. If you want both in one query, you can put both COUNTs together, since you're using the same GROUP BY regardless.
You could use a CASE statement within your query to change the max number of service_names.
See MySQL CASE statement reference
To do this in the SQL itself would be quicker than evaluating it in PHP.
To count how many distinct titles you can try:
SELECT user_id, COUNT(DISTINCT name)
FROM service_titles
GROUP BY user_id