I'm not certain that this can be done, I have a table of users with a related table of user activity joined on a foreign key. Activity has different types, e.g. comment, like etc. I need to get users filtered by the number of each different type of activity.
What I have so far is this:
SELECT
users.*,
COUNT(t1.id) AS comments,
COUNT(t2.id) AS likes
FROM users
LEFT JOIN activity AS t1 ON users.id = t1.user_id
LEFT JOIN activity AS t2 ON users.id = t2.user_id
WHERE t1.activity_type_id = 1 AND t2.activity_type_id = 2
GROUP BY users.id
HAVING comments >= 5 AND likes >= 5
This seems to be close but it's returning a user with a count of 5 both likes and comments, when in reality the user has 5 likes and 1 comment.
To be clear I want this query to return users who have 5 or more likes and also users who have 5 or more comments.
UPDATE:
I've created an SQL Fiddle. In this case I have 3 users:
User 1: 6 comments, 8 likes
User 2: 3 comments, 2 likes
User 3: 5 comments, 2 likes
I want the query to return only user 1 and 3, with their respective totals of likes and comments.
http://sqlfiddle.com/#!2/dcc63/4
You can use conditional summing to do the count and due to the way MySQL treats boolean expressions an expression like sum(case when et.name = 'comment' then 1 else 0 end) (the "normal" SQL syntax) can be reduced to sum(case when et.name = 'comment').
SELECT
u.id,
sum(et.name = 'comment') AS comments,
sum(et.name = 'like') AS likes
FROM users AS u
LEFT JOIN engagements AS e ON u.id = e.user_id
JOIN engagement_types AS et ON e.engagement_type_id = et.id
GROUP BY u.id
HAVING sum(et.name = 'comment') >= 5
OR sum(et.name = 'like') >= 5
Result:
| ID | COMMENTS | LIKES |
|----|----------|-------|
| 1 | 6 | 8 |
| 3 | 5 | 2 |
Sample SQL Fiddle
Related
So I have this two table where it records what kind of food is the user's favorite:
users table
------------
id | country
------------
1 | US
2 | PH
3 | US
4 | US
5 | PH
food_favourites table
-----------------
food_id | user_id
-----------------
3 | 1
7 | 1
3 | 2
3 | 3
3 | 4
I want to know how many unique users from US tagged food_id 3 as their favorite.
So far I have this query:
select *, count(user_id) as total
from food_favourite
inner join users on users.id = food_favourites.user_id
where food_favourites.food_id = 3
and users.country = 'US'
group by users.id
Well This doesn't work coz it returns total to 4 instead of just 3.
I also tried doing subqueries - no luck, I think I'm missing something.
DROP TABLE IF EXISTS users;
CREATE TABLE users
(user_id SERIAL PRIMARY KEY
,country CHAR(2) NOT NULL
);
INSERT INTO users VALUES
(1,'US'),
(2,'EU'),
(3,'US'),
(4,'US'),
(5,'EU');
DROP TABLE IF EXISTS favourite_foods;
CREATE TABLE favourite_foods
(food_id INT NOT NULL
,user_id INT NOT NULL
,PRIMARY KEY(food_id,user_id)
);
INSERT INTO favourite_foods VALUES
(3,1),
(7,1),
(3,2),
(3,3),
(3,4);
SELECT COUNT(DISTINCT u.user_id) distinct_users
FROM users u
JOIN favourite_foods f
ON f.user_id = u.user_id
WHERE u.country = 'US'
AND f.food_id = 3;
+----------------+
| distinct_users |
+----------------+
| 3 |
+----------------+
First of all the answer to the above question should be 3 as id 1,3,4 all have food_id 3 as their favorite food.
To just print the query try this, it will surely work:
select count(*) as total from food_favourites
inner join users on users.id=food_favourites.user_id
where food_id=3 and country='US';
I want to know how many unique users from US tagged food_id 3 as their favorite.
You count unique values with COUNT DISTINCT:
select count(distinct ff.user_id) as total
from food_favourite ff
inner join users u on u.id = ff.user_id
where ff.food_id = 3
and u.country = 'US';
Don't group by user, because you don't want a result per user. You want one row with one number, telling you how many US users prefer food 3.
An alternative that I prefer over the join. The query reads like I would word the task: count users from US that like food 3.
select count(*) as total
from users
where country = 'US'
and id in (select user_id from food_favourites where food_id = 3);
No unnecessary join and hence no need to get back to distinct values.
The sub_query is
SELECT u.country, f.food_id, COUNT(u.id) AS 'Total users'
FROM users u
INNER JOIN food_favourites AS f ON (u.id = f.[user_id])
WHERE u.country = 'US'
GROUP BY u.country, f.food_id
select count(user_id) as total, Country
from food_favourites
inner join users on users.id = food_favourites.user_id
where food_favourites.food_id = 3
and users.country = 'US'
group by country
Untested, but I think this is what you're after? This will return results only for the US and a food id of 3. If you want something more reusable that you can simply loop through the results for ALL countries...something like this should work (once again, untested...):
select count(user_id) as total, Country, food_id
from food_favourites
inner join users on users.id = food_favourites.user_id
group by country, food_id
order by country, food_id
Try:
select count(user_id) as total
from food_favourites
inner join users on users.id = food_favourites.user_id
where food_favourites.food_id = 3
and users.country = 'US'
I'm having an issue with a query of mine and how it's being joined. I need to pull some data from multiple tables in regards to CSR agents and the number of dealers they are associated with.
As shown below, I need to return a number of daily contact records for each user as well as a number of dealers associated with that number. Eventually I need to use a formula made from these 1 values, but I can do that with no problem I'm just having an issue getting the two values appropriately.
Currently, I'm getting the same number for both count values, where they should be different.
The code:
SELECT
c.user AS UserID,
COUNT(*) AS NumberOfDailyContacts, -- number of records in contact_events for this user
COUNT(d.csr) AS NumberOfDealerContacts, -- number of dealers associated with this user
FROM contact_events c
JOIN users u
ON c.user = u.id
JOIN dealers d
ON c.dealer_num = d.dealer_num
LEFT JOIN attr_list al
ON d.csr = al.data
GROUP BY UserID;
The fiddle: http://sqlfiddle.com/#!9/bd375/1
Desired output:
12345 | 2 | 3
23456 | 2 | 6
34567 | 2 | 2
45678 | 2 | 2
56789 | 2 | 5
67890 | 2 | 2
78911 | 2 | 4
But currently the fiddle is giving me all 2's for both columns.
The table structure for these tables sucks but it's what I'm given currently. The problem is that the contact events table uses the user ID for the CSR, where the dealer table associates by the 'data' value on the attribute_list table. So I basically have to say:
If the user ID In the contact_events table matches the user_id for a given data field in attr_list, show dealers associated with that user.
Hopefully the fiddle makes this a little more clear but I'll answer any questions you may have.
Use a subquery that joins attr_list with dealers to get the number of dealers per user.
select
c.user as UserID,
count(*) as NumberOfDailyContacts,
al.NumberOfDealerContacts
From contact_events c
join users u
on c.user = u.id
join dealers d
on c.dealer_num = d.dealer_num
left join (
SELECT user_id, COUNT(*) AS NumberOfDealerContacts
FROM attr_list AS al
JOIN dealers AS d ON d.csr = al.data
GROUP BY user_id) AS al
ON al.user_id = c.user
GROUP BY UserID
fiddle
Your joins were out of order, which caused your counts to get messed up. Here's what it should be, no subqueries needed:
SELECT
u.id AS UserID
,COUNT(DISTINCT c.id) AS NumberOfDailyContacts
,COUNT(DISTINCT d.dealer_num) AS NumberOfDealerContacts
FROM users u
LEFT JOIN attr_list al ON u.id = al.user_id
LEFT JOIN dealers d ON d.csr = al.data
LEFT JOIN contact_events c ON c.user = u.id
GROUP BY u.id;
i know that stackoverflow is remember answer for this question, but I have a bit different situation.
I have a lot cells in second table, but SQL query get only first. Ok, not all query, only WHERE tag.
Ex:
1 table:
user_id = 1
user_id = 2
2 table:
user_id = 1 | year = 2015 | rating = 55
user_id = 1 | year = 2016 | rating = 10
user_id = 2 | year = 2016 | rating = 50
user_id = 2 | year = 2016 | rating = 5
SQL query:
$query = "SELECT c.*,v.upvotes
FROM ".PREFIX."_users c
LEFT JOIN (SELECT user_id,pol,vid_sporta,year_sport,category,SUM(rating) as upvotes
FROM ".PREFIX."_userrating
GROUP BY user_id
) v
ON c.user_id = v.user_id
WHERE year_sport='2015'
ORDER BY upvotes DESC";
This query give me only one user, whitch has 2015 first.
I need some while cycle in SQL query :)
Help, please :)
It appears that there maybe a couple of issues going on.
First,
SELECT user_id,pol,vid_sporta,year_sport,category,SUM(rating) as upvotes
SHOULD BE
SELECT user_id,SUM(rating) as upvotes
You only want to include the columns that you are returning to the rest of your query and any column that is not apart of an aggregate function must also appear in your GROUP BY statement.
Second and this is why you may only be getting 1 record is the location of your WHERE year_sport = '2015'. Because the where condition is in the outer query it is treating your LEFT JOIN as an INNER JOIN and limiting to all results that have that year_sport in userrating. Move the where statement to your inner query and you should get all of your users but only upvotes from year_sport =2015.
$query = "SELECT c.*,v.upvotes
FROM ".PREFIX."_users c
LEFT JOIN (SELECT user_id,SUM(rating) as upvotes
FROM ".PREFIX."_userrating
WHERE year_sport='2015'
GROUP BY user_id
) v
ON c.user_id = v.user_id
ORDER BY upvotes DESC";
I cannot find the answer to my problem here on stackoverflow. I have a query that spans 3 tables:
newsitem
+------+----------+----------+----------+--------+----------+
| Guid | Supplier | LastEdit | ShowDate | Title | Contents |
+------+----------+----------+----------+--------+----------+
newsrating
+----+----------+--------+--------+
| Id | NewsGuid | UserId | Rating |
+----+----------+--------+--------+
usernews
+----+----------+--------+----------+
| Id | NewsGuid | UserId | ReadDate |
+----+----------+--------+----------+
Newsitem obviously contains newsitems, newsrating contains ratings that users give to newsitems, and usernews contains the date when a user has read a newsitem.
In my query I want to get every newsitem, including the number of ratings for that newsitem and the average rating, and how many times that newsitem has been read by the current user.
What I have so far is:
select newsitem.guid, supplier, count(newsrating.id) as numberofratings,
avg(newsrating.rating) as rating,
count(case usernews.UserId when 3 then 1 else null end) as numberofreads from newsitem
left join newsrating on newsitem.guid = newsrating.newsguid
left join usernews on newsitem.guid = usernews.newsguid
group by newsitem.guid
I have created an sql fiddle here: http://sqlfiddle.com/#!9/c8add/8
Both count() calls don't return the numbers I want. numberofratings should return the total number of ratings for that newsitem (by all users). numberofreads should return the number of reads for the current user for that newsitem.
So, newsitem with guid d104c330-c319-40e8-8be3-a7c4f549d35c should have 2 ratings and 3 reads for the current user with userid = 3.
I have tried conditional counts and sums, but no success yet. How can this be accomplished?
The main problem that I see is that you're joining in both tables together, which means that you're going to effectively be multiplying out by both numbers, which is why your counts aren't going to be correct. For example, if the Newsitem has been read 3 times by the user and rated by 8 users then you're going to end up getting 24 rows, so it will look like it has been rated 24 times. You can add a DISTINCT to your COUNT of the ratings IDs and that should correct that issue. Average should be unaffected because the average of 1 and 2 is the same as the average of 1, 1, 2, & 2 (for example).
You can then handle the reads by adding the userid to the JOIN condition (since it's an OUTER JOIN it shouldn't cause any loss of results) instead of in a CASE statement for your COUNT, then you can do a COUNT on distinct id values from Usernews. The resulting query would be:
SELECT
I.guid,
I.supplier,
COUNT(DISTINCT R.id) AS number_of_ratings,
AVG(R.rating) AS avg_rating,
COUNT(DISTINCT UN.id) AS number_of_reads
FROM
NewsItem I
LEFT OUTER JOIN NewsRating R ON R.newsguid = I.guid
LEFT OUTER JOIN UserNews UN ON
UN.newsguid = I.guid AND
UN.userid = #userid
GROUP BY
I.guid,
I.supplier
While that should work, you might get better results from a subquery, as the above needs to explode out the results and then aggregate them, perhaps unnecessarily. Also, some people might find the below to be a little clearer.
SELECT
I.guid,
I.supplier,
R.number_of_ratings,
R.avg_rating,
COUNT(*) AS number_of_reads
FROM
NewsItem I
LEFT OUTER JOIN
(
SELECT
newsguid,
COUNT(*) AS number_of_ratings,
AVG(rating) AS avg_rating
FROM
NewsRating
GROUP BY
newsguid
) R ON R.newsguid = I.guid
LEFT OUTER JOIN UserNews UN ON UN.newsguid = I.guid AND UN.userid = #userid
GROUP BY
I.guid,
I.supplier,
R.number_of_ratings,
R.avg_rating
I'm with Tom you should use a subquery to calculate the user count.
SQL Fiddle Demo
SELECT NI.guid,
NI.supplier,
COUNT(NR.ID) as numberofratings,
AVG(NR.rating) as rating,
user_read as numberofreads
FROM newsitem NI
LEFT JOIN newsrating NR
ON NI.guid = NR.newsguid
LEFT JOIN (SELECT NewsGuid, COUNT(*) user_read
FROM usernews
WHERE UserId = 3 -- use a variable #user_id here
GROUP BY NewsGuid) UR
ON NI.guid = UR.NewsGuid
GROUP BY NI.guid,
NI.supplier,
numberofreads;
table 1
id | question
1 | who will win the election
table 2
id | answers | question id
1 | I will | 1
table 3
id | photo | question id
1 | xy.gif| 1
table 4 * users can both suggest questions and vote for others
id | username
1 | joe
table 5
id | vote | question_id | user_id
1 | He | 1 | 1
What is the query that will get me the following information in one query
t1.* (all the questions)
t2 all the answers connected to the questions
t3 all the photos related to the questions
t4 usernames of the author for each question
t5 the votes for the questions (it is possible that some questions will not have a vote of the logged in user)
my problem is the last point, getting the votes (while not all questions have votes by the specific logged user)
Here is how my query looks like:
SELECT
poll_questions.id,
poll_questions.question,
poll_questions.qmore,
poll_questions.total_votes,
poll_questions.active,
poll_questions.created_at,
poll_answers.answer,
poll_answers.votes,
poll_answers.id AS answer_id,
poll_photos.photo_name_a,
vote_history_raw.vote,
users.username
FROM poll_questions
LEFT JOIN (poll_answers, poll_photos)
ON (poll_answers.question_id = poll_questions.id AND
poll_photos.question_id = poll_questions.id
)
LEFT JOIN users ON poll_questions.author = users.id
INNER JOIN vote_history_raw ON users.id = vote_history_raw.user_id
WHERE poll_questions.active = 1
ORDER BY poll_questions.created_at DESC
thanks much!
Didn't try it, but does this work?
SELECT
poll_questions.id,
poll_questions.question,
poll_questions.qmore,
poll_questions.total_votes,
poll_questions.active,
poll_questions.created_at,
poll_answers.answer,
poll_answers.votes,
poll_answers.id AS answer_id,
poll_photos.photo_name_a,
vote_history_raw.vote,
users.username
FROM poll_questions
LEFT JOIN (poll_answers, poll_photos)
ON (poll_answers.question_id = poll_questions.id AND
poll_photos.question_id = poll_questions.id
)
LEFT JOIN users ON poll_questions.author = users.id
LEFT JOIN vote_history_raw ON (users.id = vote_history_raw.user_id OR users.id <> vote_history_raw.user_id AND vote_history_raw.user_id IS NOT NULL)
WHERE poll_questions.active = 1
ORDER BY poll_questions.created_at DESC