MySQL Sort Query - mysql

I have a (what I am hoping to be easy) problem with a MySQL query.
I have 2 tables: articles, comments
An article can have many comments so there is a foreign of article_id in the comments table.
I want to get all the articles and while loop them to show on the page and then get all the comments count for each article. Easy, this is done. Now the problem is I want to sort the results based on number of comments but still show the results in the same way.
So basically I want to:
SELECT *
FROM tbl_articles
JOIN tbl_comments
ORDER BY (the most comments);
I am hoping this can all be done in a single query as the entire query is build dynamically from multiple sets of checkboxes where a single query could look like:
SELECT *
FROM tbl_articles
WHERE subject IN (1,2,5)
AND medium IN (1,3)
AND date_active > NOW()
AND...
Any further information I am happy to provide.

Something like...
SELECT *, COUNT(tbl_comments.id) as comments_count
FROM tbl_articles JOIN tbl_comments ON (tbl_comments.article_id = tbl_articles.id)
GROUP BY tbl_comments.article_id
ORDER BY comments_count;

Related

Multitable counting and multiplying in same query

I have got a somewhat complicated problem. This is my situation (ERD).
For a dashboard i need to create a pivot table that shows me the total amount of competences used by the vacancies. Therefore I need to:
Count the amount of vacancies per template
Count the amount of templates per competence
and last: multiply these numbers to get the total amount of comps used.
I have the first query:
SELECT vacancytemplate_id, count(id)
FROM vacancies
group by vacancytemplate_id;
And the second query isn't that difficult either, but I don't know what the right solution will be. I'm literally brainstuck. My mind can't comprehend how I can achieve the next step and put it down in a query. Please kind stranger, help me out :)
EDIT: my desired result is something like this
NameOfComp, NrOfTimesUsed
Leading, 17
Inspiring, 2
EDIT2: the meta query it should look like:
SELECT NameOfComp, (count of the competences used by templates) * (number of vacancies per template)
EDIT3: http://sqlfiddle.com/#!9/2773ca SQLFiddle
Thanks a lot!
If I am understanding your request correctly, you are wanting a count of competences per vacancy. This can be done very simply due to your table structure:
Select v.ID, count(*) from vacancy as v inner join CompTemplate_Table as CT
on v.Template_ID = CT.Template_ID group by v.ID;
The reason you can do only one join is because there will be a record in the CompTemplate_Table for every competency in each template. Additionally, the same key is used to join vacancy to templates as is used to join templates to CompTemplate_Table, so they represent the same key value (and you can skip joining the Templates table if you don't need data from there).
If you are wanting to add this data to a pivot table, I will leave that exercise to you. There are a number of tutorials available if you do a quick google search and it should not be that hard.
UPDATE: For the second query you are looking at something like:
Select cp.NameOfComp, count(*) from vacancy as v inner join CompTemplate_Table as CT
on v.Template_ID = CT.Template_ID inner join competencies as CP
on CP.ID = CT.Comp_ID
group by CP.NameOfComp
The differences here are you are adding in the comptetencies table, as you need data from that, and grouping by the CP.NameOfComp instead of the vacancy id. You can also restrict this to specific templates, competencies, or vacancies by adding in search conditions (e.g. where CP.ID = 12345)

select count as a computed column?

I have a table named "likes" with this structure:
id - auto generated number,
bywho - user that likes someone ,
identifier - the liked user,
tip - the category of the like
i'm trying make a list with the most liked users(identifier), my problem is:
i need to generate the ammount of likes as a computed column in the list...
here is what i tried:
SELECT u.bywho,u.identifier COUNT(DISTINCT inv_by.identifier) AS lol
FROM likes u
LEFT JOIN likes inv_by ON u.identifier = inv_by.identifier
WHERE inv_by.identifier= $this->who AND tip='profil'
GROUP BY u.identifier ORDER BY lol DESC
I expect this isn't working because of the missing comma and grouping hasn't occured by u.bywho. The problem with doing that is it will give you a breakdown of the count by the person being liked and who liked them. Assuming a person can never be liked more than once, the count would always be one.
Try adding the comma after u.identiier in the select clause as mentioned by another reply.
If that doesn't work try grouping by u.who as well.
If that doesn't work as expected please explain what you expect a liitle more.
I'm guessing you may want to remove something from the select clause. Whatever non-aggregate is left in the select clause needs to be grouped upon.

MySQL sorting by "relationships per day"

I need to create a mysql query for my project that's a bit too complicated for my scope...
So, I a table of images with id and timestamp columns, along with metadata columns
I also have a table of "loves", which has columns for id, imageid, userid, and timestamp
(userid not really important here)
Currently, I am using a LEFT JOIN to sort the images by their total number of likes
What I would like to do now is, instead, sort the images by their daily average of likes.
So, an image created today that has 5 likes associated with it should come before an image created 5 days ago with 20 likes associated.
Not even sure how to begin to approach this, any of you SQL gurus have any ideas? Cheers.
EDIT:
Using this query
SELECT images.*,
COUNT(loves.id) AS num_loves
FROM images
JOIN loves ON (images.id = loves.imageid)
GROUP BY images.id
ORDER BY num_loves/DATEDIFF(images.timestamp,CURDATE())
DESC LIMIT 0 , 24
getting this error
Reference 'num_loves' not supported (reference to group function)
Still getting a handle on MySQL syntax...
You can use any valid expression as your ORDER BY clause. This means we just need to recall a hint of algebra:
SELECT
images.url,
images.date_added
FROM IMAGES
JOIN image_likes ON image_likes.image_id = images.id
GROUP BY images.id
ORDER BY count(image_likes.id)/DATEDIFF(CURDATE(), images.date_added)

order by count from another table

I hope itll be legal to post this as i'm aware of other similar posts on this topic. But im not able to get the other solutions to work, so trying to post my own scenario. Pretty much on the other examples like this one, im unsure how they use the tablenames and rows. is it through the punctuation?
SELECT bloggers.*, COUNT(post_id) AS post_count
FROM bloggers LEFT JOIN blogger_posts
ON bloggers.blogger_id = blogger_posts.blogger_id
GROUP BY bloggers.blogger_id
ORDER BY post_count
I have a table with articles, and a statistics table that gets new records every time an article is read. I am trying to make a query that sorts my article table by counting the number of records for that article id in the statistics table. like a "sort by views" functions.
my 2 tables:
article
id
statistics
pid <- same as article id
Looking at other examples im lacking the left join. just cant wrap my head around how to work that. my query at the moment looks like this:
$query = "SELECT *, COUNT(pid) AS views FROM statistics GROUP BY pid ORDER BY views DESC";
Any help is greatly appreciated!
SELECT article.*, COUNT(statistics.pid) AS views
FROM article LEFT JOIN statistics ON article.id = statistics.pid
GROUP BY article.id
ORDER BY views DESC
Ideas:
Combine both tables using a join
If an article has no statistics, fill up with NULL, i.e. use a left join
COUNT only counts non-NULL values, so count by right table to give correct zero results
GROUP BY to obtain exactly one result row for every article, i.e. to count statistics for each article individually

Complex MySQL Query - Find duplicates PER user_id?

I have a database of Facebook Likes from several people. There are duplicate "like_id" fields across many "user_id"s. I want a query that will find the amount of "like_id"s person A has in common with person B.
This query is fantastic for comparing likes when only 2 "user_id"s are in the database, but as soon as I add a 3rd, it messes it up. Basically, I want to see who has the most "likes" in common with with person A.
SELECT *,
COUNT(*)
FROM likes
GROUP BY like_id
HAVING COUNT(*) > 1
Anyone have a query that might work?
This SQL should work. You just need to put in the User A's user_id and it should compare with all other users and show the top matching one. You can change it to show the top 5 or do whatever else you need to do.
Basically what it is doing is that it is doing a self join on the table, but making sure that when it does a join, it is a different user_id but the "like" is the same. Then it does a group by each of the other user_id's and sums the same amount of likes for that user_id.
SELECT all_other_likes.user_id, count(all_other_likes.like_id) AS num_similar_likes
FROM likes original_user_likes
JOIN likes all_other_likes
ON all_other_likes.user_id != original_user_likes.user_id
AND original_user_likes.like_id = all_other_likes.like_id
WHERE original_user_likes = USER_ID_YOU_WANT_TO_COMPARE
GROUP BY all_other_likes.user_id
ORDER BY count(all_other_likes.like_id) DESC
LIMIT 1;
Not sure what database you are using. You might need to do a SELECT TOP 1 if it is MS-SQL, but this is valid PostgreSQL and MySQL syntax.
I think this will do it:
SELECT
likes_a.user_id,
likes_b.user_id
FROM
likes as likes_a JOIN likes as likes_b
ON
likes_a.like_id = likes_b.like_id
WHERE
likes_a.user_id <> likes_b.user_id
And then post-process the results to count up who has the most in common.