Sum Two Columns in Two Mysql Tables - mysql

I've been searching everywhere for this but no cigar. Smoke is starting to come out of my ears. please help
How do you sum two columns in two tables and group by userid?
Have two tables.
Recipe Table
recipeid userid recipe_num_views
Meals Table
mealsid userid meal_num_views
Goal is to sum the num views in both tables and group by userid
so for example
Recipe Table
1 3 4
2 4 6
Meal Table
1 3 2
2 4 5
select sum(recipe views)+sum(meal views)
WHERE recipe.userid=meals.userid GROUP BY userid
should give
userid=3 , sum=6
userid=4, sum=11
this gives a much bigger number.

SELECT recipe.userid, sum(recipe_num_views+meal_num_views)
FROM Recipe JOIN Meals ON recipe.userid=meals.userid
GROUP BY recipe.userid
EDIT:
OK, from your comments, I understand that when you have for user 3: 4 recipes & 3 meals you will get the sum of the combination of all these rows => sum(recipes)*3 + sum(meals)*4
Try this query instead:
select r.userid, (sum_recipe + sum_meal) sum_all
FROM
(select userid, sum(recipe_num_views) sum_recipe
FROM Recipe
GROUP BY userid) r
JOIN (
select userid, sum(meal_num_views) sum_meal
FROM Meals
GROUP BY userid) m ON r.userid = m.userid

If you're selecting from 2 tables you need to join them.
Otherwise MySQL will not know how to link up the two tables.
select sum(recipe_num_views + meal_num_views)
from recipe r
inner join meals m ON (r.user_id = m.user_id)
group by m.user_id
See:
http://dev.mysql.com/doc/refman/5.5/en/join.html
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Related

Select ID of a row with max value

How can I select the ID of a row with the max value of another column in a query that joins multiple tables?
For example, say I have three tables. tblAccount which stores a grouping of users, like a family. tblUser which stores the users, each tied to a record from tblAccount. And each user can be part of a plan, stored in tblPlans. Each plan has a Rank column that determines it's sorting when comparing the levels of plans. For example, Lite is lower than Premium. So the idea is that each user can have a separate plan, like Premium, Basic, Lite etc..., but the parent account does not have a plan.
How can I determine the highest plan in the account with a single query?
tblAccount
PKID
Name
1
Adams Family
2
Cool Family
tblUsers
PKID
Name
AccountID
PlanID
1
Bob
1
3
2
Phil
2
2
3
Suzie
2
1
tblPlans
PKID
Name
Rank
1
Premium
3
2
Basic
2
3
Elite
4
4
Lite
1
Here's the result I'm hoping to produce:
AccountID
Name
HighestPlanID
PlanName
2
Adams Family
1
Premium
I've tried:
SELECT U.AccountID, A.Name, MAX(P.Rank) AS Rank, P.PKID as HighestPlanID, P.Name as PlanName
FROM tblPlans P
INNER JOIN tblUsers U ON U.PlanID = P.PKID
INNER JOIN tblAccounts A ON U.AccountID = A.PKID
WHERE U.AccountID = 2
and the query will not always work, selecting the MAX of Rank does not select entire row's values from tblPlans.
I am looking for a solution that is compatible with mysql-5.6.10
You can join the tables and use ROW_NUMBER() to identify the row you want. Then filtering is ieasy.
For example:
select *
from (
select a.*, p.*,
row_number() over(partition by a.pkid order by p.rank desc) as rn
from tblaccount a
join tblusers u on u.accountid = a.pkid
join tblplans p on p.pkid = u.planid
) x
where rn = 1
Inside the subquery you can add where u.accountid = 2 to retrieve a single account of interest, instead of all of them.
With the help of #the-impaler, I massaged their answer a bit and came out with something very similar:
select *
from (
select a.*, p.*
from tblaccount a
join tblusers u on u.accountid = a.pkid
join tblplans p on p.pkid = u.planid
where u.accountid = 2
order by p.rank desc
) x limit 1
The subquery sorts each user by plan rank from top to bottom, and then the top level query selects the top most row with limit 1. It seems to work!

Getting Average based on distinct row in mysql

I have a table users containing the fields userID,age,gender and i have another table
name as click_info containing fields(id,userID,clickID) The enrty in the click_info table are as following
id userID dubID
1 1 2
2 1 2
3 1 2
4 2 2
5 2 2
6 3 2
7 4 2
Now I want the average age of all the users who clicked on dubID 2 and i am using the following query
SELECT DISTINCT `dub_clickinfo`.`userID`, `users`.`age` AS `average`, `users`.*
FROM `dub_clickinfo` INNER JOIN `users` ON dub_clickinfo.userId = users.userID
WHERE (dubID=2)
The above query gives the incorrect average it will include the duplicate userID (like it will include userID 1 three times,2 two times) as well.
Please suggest a query
Thanks In Advance !!
Give it a try ,there is a one to many relation so you need to use left join not inner ,and apply a group function on user's id
SELECT dub_clickinfo.userID, users.age AS average, users.* FROM dub_clickinfo
LEFT JOIN users ON dub_clickinfo.userId = users.userID WHERE (dubID=2)
GROUP BY users.userID
try this
SELECT avg(age) FROM users WHERE userID in (select distinct userID from dub_clickinfo where dubID ='2')

MySql Wrong command

I have two tables in the sql:
client
id first
1 david
2 jenna
3 ben
rating
id clientid userid rating ratetext date
1 1 3 4 Very good 12/4/2012
2 3 6 3 Simple bla bla 5/3/2013
And i want to get all the rating for a userid
so i try something like:
SELECT rating,ratetext,date,first FROM rating r
INNER JOIN client c ON r.userid = 3;
But i always get the rows with other rows that i don't need to get. any idea what is wrong with my command?
SELECT rating, ratetext, date, first
FROM rating r INNER JOIN client c
ON r.clientid = c.id
WHERE r.userid = 3;
Presumably you want to select ratings with the explicitly specified ID, and the corresponding clients because on the clientid stored in the rating record:
SELECT rating,ratetext,date,first FROM rating r
INNER JOIN client c ON c.id = r.clientid
WHERE r.userid = 3;
Your joins should describe what two pieces of information connects the two tables. You want something along the lines of:
SELECT * FROM rating r, client c WHERE r.clientid=c.id AND r.userid=3
I believe this is what you are looking for:
SELECT r.rating, r.ratetext, r.date, c.first
FROM rating AS r
INNER JOIN client AS c
ON r.clientid = c.id
WHERE r.userid = 3
You should join on the client id columns of the two tables and then use userid in where clause to filter.
Make sure you have indexes on r.clientid and r.userid.

mysql query 3 tables

SELECT favourites.FavouriteID,
favourites.User,
favourites.RecipeID,
recipes.RecipeID,
recipes.Name,
recipes.CategoryID,
recipes.RatingTotal,
recipes.ImageMed,
count(ratings.RecipeID) AS trates ,
(recipes.RatingTotal / COUNT(ratings.RecipeID)) as avg
FROM favourites
RIGHT JOIN recipes
on recipes.RecipeID = favourites.RecipeID
LEFT JOIN ratings
ON ratings.RecipeID = recipes.RecipeID
WHERE favourites.user = '$Cuser'
GROUP BY ratings.RecipeID
ORDER BY avg DESC, trates DESC
LIMIT $offset,20
hi there this query brings through a total of 3 records but they are 7 , there other 4 don't come through as they do not have a record in the ratings table, how can i adjust ?
the favourites table conatains the recipe id of a recipe which a user has added to theor favourites list , i am trying in the query to display the recipes from the favourites table orded by the one's withthe highet raring first. but the ones that do not have a rating are not showing
The error seems to be in the data. Maybe the relational integrity between favourites and recipes is violated. Show your test data.

MYSQL PHP count lines in two tables with one query

I would like to count entries (lines) from two tables WHERE (in both) user_id is 12 and club is 5,8,19. I need to receive values (or array it does not matter) for each club, example (5=>24, 8=>78, 19=>56). How can I write this query please?
thank you.
Assume your tables are: user and club.
SELECT c.club_id, COUNT(*)
FROM user u, club c
WHERE u.user_id = 12
AND c.club_id IN (5,8,19)
AND u.club_id = c.club_id
GROUP BY c.club_id
SELECT COUNT(*) as num_rows FROM my_table WHERE user_id = 12 AND club_id in (5,8,19) GROUP BY club_id