i have query
SELECT P.*, COUNT(L.to) AS likes, U.name AS ownerName, U.username AS ownerUsername,
U.picture AS ownerPicture
FROM sn_posts P LEFT JOIN sn_users AS U
ON U.id = P.ownerID
LEFT JOIN sn_likes AS L
ON L.to = P.id
WHERE (P.ownerID = 69)
GROUP BY P.id
ORDER BY P.id DESC
it's taking - 0.3337 sec time,
Add an index for table sn_posts with ownerID field may
be nicer
Related
I have the following query:
SELECT u.id, u.name, u.date_registered, p.time_created
FROM users u JOIN
prospect_notes p
ON u.id=p.subject_id
WHERE u.allocated_instructors = 668
AND p.time_created = (SELECT MAX(p2.time_created) FROM prospect_notes p2 WHERE p2.subject_id = p.subject_id)
ORDER BY p.time_created;
My problem is that when there are no rows in the prospect_notes table which match the following:
AND p.time_created = (SELECT MAX(p2.time_created) FROM prospect_notes p2 WHERE p2.subject_id = p.subject_id)
I get no result.
Instead, I want all the rows in the users table to return (presumably p.time_created would be NULL in such cases).
You need to be careful because of the JOIN clause. Presumably, if there are no matches for the correlated subquery, there are no matches in the JOIN either.
So, use LEFT JOIN and move the logic to the FROM clause:
SELECT u.id, u.name, u.date_registered, p.time_created
FROM users u LEFT JOIN
prospect_notes p
ON u.id = p.subject_id LEFT JOIN
(SELECT p2.subject_id, MAX(p2.time_created) as max_time_created
FROM prospect_notes p2
GROUP BY p2.subject_id
) p2
ON p2.subject_id = p.subject_id AND p2.time_created = p.time_created
WHERE u.allocated_instructors = 668
ORDER BY p.time_created;
That said, if you only want time_created from prospect_notes, then use a simpler query:
SELECT u.id, u.name, u.date_registered, MAX(p.time_created)
FROM users u LEFT JOIN
prospect_notes p
ON u.id = p.subject_id
WHERE u.allocated_instructors = 668
GROUP BY u.id -- okay, assuming id is unique or a primary key
ORDER BY MAX(p.time_created);
You need LEFT JOIN this clause permit you to have NULL values in the right table.
Try :
SELECT u.id, u.name, u.date_registered, p.time_created
FROM users u
LEFT JOIN prospect_notes p
ON u.id=p.subject_id
WHERE u.allocated_instructors = 668
AND p.time_created = (SELECT MAX(p2.time_created) FROM prospect_notes p2 WHERE p2.subject_id = p.subject_id)
ORDER BY p.time_created;
I have a Spring MVC blog with functionality for Post and Comment voting. I want to return the top 3 users based on number of votes they've received on all their posts and comments.
tables:
users u [id, username]
posts p [id, u.id]
comments c [id, p.id, u.id]
post_votes pv [p.id, u.id, type (1 or -1)]
comment_votes cv [c.id, u.id, type (1 or -1)]
The following statement gives me total votes per user by querying two separate voting tables and then adding the totals together:
SELECT
(SELECT SUM(type)
FROM posts_votes pv
JOIN posts p ON p.id = pv.post_id
JOIN users u ON u.id = p.user_id
WHERE u.id LIKE ?1)
+
(SELECT SUM(type)
FROM comments_votes cv
JOIN comments c ON c.id = cv.comment_id
JOIN users u ON u.id = c.user_id
WHERE u.id LIKE ?1)
That works fine with a WHERE clause per user id... But now I'm trying to find just the top 3 users that have the most votes and I'm having too much difficulty. This is what I have so far:
SELECT u.id, u.username, IFNULL(SUM(pv.type), 0) AS totalPostVotes
FROM posts_votes pv
JOIN posts p ON p.id = pv.post_id
JOIN users u ON u.id = p.user_id
GROUP BY u.id ORDER BY totalPostVotes DESC LIMIT 3
That above statement works by itself giving me: u.id, u.username, and totalPostVote in descending order. So does the one below for comments:
SELECT u.id, u.username, IFNULL(SUM(cv.type), 0) AS totalCommentVotes
FROM comment_votes cv
JOIN comments c ON c.id = cv.comment_id
JOIN users u ON u.id = c.user_id
GROUP BY u.id ORDER BY totalCommentVotes DESC LIMIT 3
Great! But I want that third column SUM result to be essentially "totalVotes" and contain the sum of both of those subqueries. Then I'll GROUP BY u.id ORDER BY totalVotes DESC LIMIT 3.
Something like this:
SELECT u.id, u.username, SUM(
(SELECT IFNULL(SUM(pv.type), 0) AS totalPostVotes
FROM posts_votes pv
JOIN posts p ON p.id = pv.post_id
JOIN users u ON u.id = p.user_id
GROUP BY u.id ORDER BY totalPostVotes DESC LIMIT 1)
+
(SELECT IFNULL(SUM(cv.type), 0) AS totalCommentVotes
FROM comments_votes cv
JOIN comments c ON c.id = cv.comment_id
JOIN users u ON u.id = c.user_id
GROUP BY u.id ORDER BY totalCommentVotes DESC LIMIT 1))
AS totalVotes from users u
GROUP BY u.id, u.username ORDER BY totalVotes DESC LIMIT 3
id | username | totalVotes
2 user2 11
1 user1 11
29 user29 11
What's happening is the result of totalVotes is indeed the correct vote count, 11, for the "top" user, but none of those users are the real top user, and the correct vote is being repeated 3 times in the guise of other users. I'm not even sure how users are being sorted at that point because they're not in an order I recognize.
The subqueries work separately (they give me the correct user) when I add SELECT "u.id, u.username " IFNULL(SUM()) but then if I run the whole block, I get the error "Operand should contain 1 column(s)" So I delete them and revert to only SELECT IFNULL(SUM())
I'm also noticing the subqueries are only allowed LIMIT 1. How would I get the top 3, then? Should I do a UNION somewhere or is "+" sufficient? This is rather confusing. Can someone please help me with this? Any help is appreciated. Thanks in advance!
Updated code, thank you Peter:
SELECT
u.username,
pv_sum.total AS postTotal,
cv_sum.total AS commentTotal,
IFNULL(pv_sum.total, 0) + IFNULL(cv_sum.total, 0) as totalVotes
FROM users u
LEFT JOIN (
SELECT p.user_id, IFNULL(SUM(pv.type), 0) AS total
FROM posts p
JOIN posts_votes pv ON pv.post_id = p.id
GROUP BY p.user_id
) pv_sum ON pv_sum.user_id = u.id
LEFT JOIN (
SELECT c.user_id, IFNULL(SUM(cv.type), 0) AS total
FROM comments c
JOIN comments_votes cv ON cv.comment_id = c.id
GROUP BY c.user_id
) cv_sum ON cv_sum.user_id = u.id
GROUP BY u.username, postTotal, commentTotal
ORDER BY totalVotes DESC LIMIT 3;
Don't place your subqueries in your SELECT-part, but join them on the users-table:
SELECT
u.username,
pv_sum.total AS postTotal,
cv_sum.total as commentTotal,
IFNULL(pv_sum.total, 0) + IFNULL(cv_sum.total, 0) as totalVotes
FROM users u
LEFT JOIN (
SELECT p.user_id, IFNULL(SUM(pv.type), 0) AS total
FROM posts p
JOIN post_votes pv ON pv.post_id = p.id
GROUP BY p.user_id
) pv_sum ON pv_sum.user_id = u.id
LEFT JOIN (
SELECT c.user_id, IFNULL(SUM(cv.type), 0) AS total
FROM comments c
JOIN comment_votes cv ON cv.comment_id = c.id
GROUP BY c.user_id
) cv_sum ON cv_sum.user_id = u.id
GROUP BY u.id
ORDER BY totalVotes DESC
LIMIT 3;
Fiddle: http://sqlfiddle.com/#!9/980cb2/11
Here is my query:
select u.id, u.name,
(select count(*) from users where name = u.name) as total
from users u
where u.name = 'anything'
order by id
limit 1
As you know, my query returns 1 user which has anything name. And total contains the number of all users which have anything name. Ok all fine.
Now I want to do the same thing when there are three JOINs in the query. Please assume this:
select u.id, u.name, sum(r.reputation) rep
from users u
join reputation r on u.id = r.user_id
join posts_tags pt on r.post_id = pt.post_id
join tags t on pt.tag_id = t.id
where u.name = 'anything' and t.name = 'mytag'
group by u.id, u.name
order by rep desc, u.id
limit 1
Now I want to know, how can I implement total part in this ^ query?
Try this query ,hope this give you the right result.
select * , count(id) as total from (select u.id, u.name, sum(r.reputation) rep
from users u
join reputation r on u.id = r.user_id
join posts_tags pt on r.post_id = pt.post_id
join tags t on pt.tag_id = t.id
where u.name = 'anything' and t.name = 'mytag'
group by u.id, u.name
order by rep desc, u.id
limit 1 ) as result
I have total 6 tables in which different info has been saved
Now i need a result in which get count from 5 tables and select all info from main table but if record does not exist than it must be need to return 0 instead of no row found that's the problem here
I have tried below query but didn't get success
SELECT
u.*,
COUNT(DISTINCT c.id) as comments,
COUNT(DISTINCT d.id) as dislikes,
COUNT(DISTINCT l.id) as likes,
COUNT(DISTINCT s.id) as shares,
COUNT(DISTINCT t.id) as tags
FROM
job_details as u
JOIN job_comments as c ON u.id = c.job_id
JOIN job_dislike as d ON u.id = d.job_id
JOIN job_like as l ON u.id = l.job_id
JOIN job_share as s ON u.id = s.job_id
JOIN job_tags as t ON u.id = t.job_id
WHERE
u.id = c.job_id AND
u.id = d.job_id AND
u.id = l.job_id AND
u.id = s.job_id AND
u.id = t.job_id
GROUP BY
u.id
This query is executed, but didn't get exact result.
I don't quite understand why.
I was hoping somebody here could help me out?
Thanks!
You probably didn't get the exact result because some tables may be missing values.
Although you can solve this problem with a LEFT JOIN, the safer solution is to pre-aggregate the data:
SELECT u.*, c.comments, d.dislikes, l.likes, s.shares, t.tags
FROM job_details as u LEFT JOIN
(select c.job_id, count(*) as comments from job_comments group by c.job_id
) c
ON u.id = c.job_id LEFT JOIN
(select d.job_id, count(*) as dislikes from job_dislike d group by d.job_id
) d
ON u.id = d.job_id LEFT JOIN
(select l.job_id, count(*) as likes from job_like l group by l.job_id
) l
ON u.id = l.job_id LEFT JOIN
(select s.job_id, count(*) as shares from job_share s group by s.job_id
) s
ON u.id = s.job_id LEFT JOIN
(select t.job_id, count(*) as tags from job_tags t group by t.job_id
) t
ON u.id = t.job_id;
Why is this better? Consider an id that has 5 comments, likes, dislikes, shares and tags. The JOIN approach produces an intermediate result with 5*5*5*5*5 = 3,125 intermediate rows. Things can really get out of hand for popular ids.
Use LEFT JOIN instead of JOIN. and you don't need WHERE clause since you have joined those tables. And, use IFNULL function to return 0 for null values. You need to modify you query like this :
SELECT u.id,
IFNULL(COUNT(DISTINCT c.id),0) as comments,
IFNULL(COUNT(DISTINCT d.id),0) as dislikes,
IFNULL(COUNT(DISTINCT l.id),0) as likes,
IFNULL(COUNT(DISTINCT s.id),0) as shares,
IFNULL(COUNT(DISTINCT t.id),0) as tags
FROM job_details as u
LEFT JOIN job_comments as c ON u.id = c.job_id
LEFT JOIN job_dislike as d ON u.id = d.job_id
LEFT JOIN job_like as l ON u.id = l.job_id
LEFT JOIN job_share as s ON u.id = s.job_id
LEFT JOIN job_tags as t ON u.id = t.job_id
GROUP BY u.id
SELECT
u.*,
GROUP_CONCAT(DISTINCT f.shot_id SEPARATOR ",") AS ownFavorites,
GROUP_CONCAT(DISTINCT st.shot_id SEPARATOR ",") AS ownStars,
GROUP_CONCAT(DISTINCT s.id SEPARATOR ",") AS ownShots,
( SELECT AVG(p.count)
FROM points p
LEFT JOIN shots s ON s.user_id = **U.ID** AND p.shot_id = s.id
WHERE date >= DATE_SUB(CURDATE(),INTERVAL 2 DAY)
) AS attention,
( SELECT SUM(p.count)
FROM points p
LEFT JOIN shots s ON s.user_id = **U.ID** AND s.id = p.shot_id
) AS popularity
FROM users u
LEFT OUTER JOIN shots s ON s.user_id = u.id
LEFT OUTER JOIN favorites f ON f.user_id = u.id
LEFT OUTER JOIN stars st ON st.user_id = u.id
WHERE u.username = ?;
I got two subselects which use the parameter u.id (marked in the query). If i do the sql like this it will generate somthing like that:
#1054 - Unknown column 'u.id' in 'on clause'
Means, the u.id id is NOT defined in the SubSelects. But in the MainSelect I choose from the users table, where u.id exists.
To my question: Is there a way to pass the selected u.id value to the Subselects with common sql?
Don't forget GROUP BY in the subqueries:
SELECT
u.*,
COALECSE(a.average, 0) attention,
COALESCE(p.total, 0) popular,
GROUP_CONCAT(DISTINCT f.shot_id) AS ownFavorites,
GROUP_CONCAT(DISTINCT st.shot_id SEPARATOR ",") AS ownStars,
GROUP_CONCAT(DISTINCT s.id SEPARATOR ",") AS ownShots
FROM
users u
LEFT JOIN
(
SELECT
s.user_id,
AVG(p.count) average
FROM
shots s
JOIN
points p
ON s.id = p.shot_id
WHERE
s.date >+ CURRENT_DATE - INTERVAL 2 DAY
GROUP BY s.user_id
) a
ON u.id = a.user_id
LEFT JOIN
(
SELECT
s.user_id,
SUM(p.count) total
FROM
shots s
JOIN
points p
ON s.id = p.shot_id
GROUP BY s.user_id
) p
ON u.id = p.user_id
LEFT OUTER JOIN shots s ON s.user_id = u.id
LEFT OUTER JOIN favorites f ON f.user_id = u.id
LEFT OUTER JOIN stars st ON st.user_id = u.id
WHERE u.username = 'user'
Seems like this may work. The select doesn't have knowledge of the of the users table the way you had it. I believe this would have knowledge of Users.
SELECT
u.*,
GROUP_CONCAT(DISTINCT f.shot_id SEPARATOR ",") AS ownFavorites,
GROUP_CONCAT(DISTINCT st.shot_id SEPARATOR ",") AS ownStars,
GROUP_CONCAT(DISTINCT s.id SEPARATOR ",") AS ownShots,
A.Attention, P.Popularity
FROM users u
LEFT OUTER JOIN shots s ON s.user_id = u.id
LEFT OUTER JOIN favorites f ON f.user_id = u.id
LEFT OUTER JOIN stars st ON st.user_id = u.id
LEFT OUTER JOIN
( SELECT AVG(p.count) attention
FROM points p
LEFT JOIN shots s ON s.user_id = **U.ID** AND p.shot_id = s.id
WHERE date >= DATE_SUB(CURDATE(),INTERVAL 2 DAY)
) AS A,
( SELECT SUM(p.count) popularity
FROM points p
LEFT JOIN shots s ON s.user_id = **U.ID** AND s.id = p.shot_id
) AS P
WHERE u.username = ?;
Try turning the selects into a subselect join.
FROM users u
LEFT OUTER JOIN shots s ON s.user_id = u.id
LEFT OUTER JOIN favorites f ON f.user_id = u.id
LEFT OUTER JOIN stars st ON st.user_id = u.id
LEFT OUTER JOIN ( SELECT AVG(p.count) AverageOfP, p.shot_id
FROM points p
WHERE date >= DATE_SUB(CURDATE(),INTERVAL 2 DAY)
) p ON p.shot_id = s.id
LEFT OUTER JOIN ( SELECT SUM(p.count) SumOfP, p.shot_id
FROM points p
) p2 ON p2.shot_id = s.id
The s table is already joined to u and should be good. Then in your select you can just select AverageOfP and SumOfP.