case update, two tables and count - mysql

I want to perform a case update, unfortunately I am getting an error that tells me that am making an Invalid use of group function
Error Code: 1111. Invalid use of group function
update l, m
set l.requests = sum(
case when m.event = 'rRequested' then
m.id end )
where
l.id = m.id
or
update l, m
set l.requests = (
case when m.event = 'rRequested' then
count(m.id) end )
where
l.id = m.id
Any idea how can i fix this?
I could do a full select after the set, but i want to learn how to use (even if it's possible) the case update for aggregations...

You try to distinguish based on a m.event, and the result is a grouped value (count(m.id)). I think you should sum 0 or 1 based on your value.
update l
set l.request = (select sum(if m.event = "rRequested", 0, 1) from m where m.id = l.id))
See MySQL Update query with left join and group by for the topic.
EDIT:
The question's focus seems to be avoiding the full subselect. I think since there are no real restrictions on l that the database has to go through all lines of m with event="rRequested". So I could imagine going once through m grouping by l.id:
update l
inner join
(
select id,
count(*) as cnt
from m where m.event = "rRequested"
group by id
) as grp_m on grp_m.id = l.id
set l.request = grp_m.cnt
;
It sounds a bit strange that table m has many entries with the same id, but since you gave no example, it is hard to guess.

Related

Left join sql query

I want to get all the data from the users table & the last record associated with him from my connection_history table , it's working only when i don't add at the end of my query
ORDER BY contributions DESC
( When i add it , i have only the record wich come from users and not the last connection_history record)
My question is : how i can get the entires data ordered by contributions DESC
SELECT * FROM users LEFT JOIN connections_history ch ON users.id = ch.guid
AND EXISTS (SELECT 1
FROM connections_history ch1
WHERE ch.guid = ch1.guid
HAVING Max(ch1.date) = ch.date)
The order by should not affect the results that are returned. It only changes the ordering. You are probably getting what you want, just in an unexpected order. For instance, your query interface might be returning a fixed number of rows. Changing the order of the rows could make it look like the result set is different.
I will say that I find = to be more intuitive than EXISTS for this purpose:
SELECT *
FROM users u LEFT JOIN
connections_history ch
ON u.id = ch.guid AND
ch.date = (SELECT Max(ch1.date)
FROM connections_history ch1
WHERE ch.guid = ch1.guid
)
ORDER BY contributions DESC;
The reason is that the = is directly in the ON clause, so it is clear what the relationship between the tables is.
For your casual consideration, a different formatting of the original code. Note in particular the indented AND suggests the clause is part of the LEFT JOIN, which it is.
SELECT * FROM users
LEFT JOIN connections_history ch ON
users.id = ch.guid
AND EXISTS (SELECT 1
FROM connections_history ch1
WHERE ch.guid = ch1.guid
HAVING Max(ch1.date) = ch.date
)
We can use nested queries to first check for max_date for a given user and pass the list of guid to the nested query assuming all the users has at least one record in the connection history table otherwise you could use Left Join instead.
select B.*,X.* from users B JOIN (
select A.* from connection_history A
where A.guid = B.guid and A.date = (
select max(date) from connection_history where guid = B.guid) )X on
X.guid = B.guid
order by B.contributions DESC;

SUM case returns value without GROUP BY

When I add SUM around my case select, it returns the summed value without the GROUP BY.
The query I am using, without the SUM, is the following
SELECT CASE WHEN subscription_types.type = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used
INNER JOIN training_sessions ON training_sessions.id = subscription_used.training_session_id
INNER JOIN training_series AS tserie ON tserie.id = training_sessions.training_serie_id
INNER JOIN user_training_session ON user_training_session.training_session_id = training_sessions.id
INNER JOIN subscriptions ON subscriptions.id = subscription_used.subscription_id
INNER JOIN subscription_types ON subscription_types.id = subscriptions.subscription_type_id
WHERE subscription_used.training_session_id = (SELECT training_sessions.id FROM training_sessions WHERE DATE(event_start_date) = #week_2_ago_date AND training_serie_id = 17) AND present=1
GROUP BY subscriptions.id
This query returns the values: 8,7. However, when I put a SUM around the case, it gives me the number 75. 75 is the SUM of the values that are getting returned without the GROUP BY.
Any ideas on how to fix this problem so that the query gives me the correct value (8+7 = 15, 1 row)? Thanks in advance
Group by is implying distinct values based on subscription.id so probably if you take the group by you you will get something like 8,8,8,8,8,7,7,7,7,7 due to the joins and such.
With the group by you only get the distinct values of 8 and 7. When you do sum with the group it will sum all of them though not the 2 distinct.
Most Simple fix that will give you 15:
SELECT SUM(SUBSCRIPTION_USED) FROM (
SELECT CASE WHEN subscription_types.type = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used
INNER JOIN training_sessions ON training_sessions.id = subscription_used.training_session_id
INNER JOIN training_series AS tserie ON tserie.id = training_sessions.training_serie_id
INNER JOIN user_training_session ON user_training_session.training_session_id = training_sessions.id
INNER JOIN subscriptions ON subscriptions.id = subscription_used.subscription_id
INNER JOIN subscription_types ON subscription_types.id = subscriptions.subscription_type_id
WHERE subscription_used.training_session_id = (SELECT training_sessions.id FROM training_sessions WHERE DATE(event_start_date) = #week_2_ago_date AND training_serie_id = 17) AND present=1
GROUP BY subscriptions.id);
Probably a better way to write it in general though.
EDIT: You could also do SUM(DISTINCT CASE......) if you only want to sum distinct values.

How to optimize this complected query?

While working with following query on mysql, Its getting locked,
SELECT event_list.*
FROM event_list
INNER JOIN members
ON members.profilenam=event_list.even_loc
WHERE (even_own IN (SELECT frd_id
FROM network
WHERE mem_id='911'
GROUP BY frd_id)
OR even_own = '911' )
AND event_list.even_active = 'y'
GROUP BY event_list.even_id
ORDER BY event_list.even_stat ASC
The Inner query inside IN constraint has many frd_id, So because of that above query is slooow..., So please help.
Thanks.
Try this:
SELECT el.*
FROM event_list el
INNER JOIN members m ON m.profilenam = el.even_loc
WHERE el.even_active = 'y' AND
(el.even_own = 911 OR EXISTS (SELECT 1 FROM network n WHERE n.mem_id=911 AND n.frd_id = el.even_own))
GROUP BY el.even_id
ORDER BY el.even_stat ASC
You don't need the GROUP BY on the inner query, that will be making the database engine do a lot of unneeded work.
If you put even_own = '911' before the select from network, then if even_own IS 911 then it will not have to do the subquery.
Also why do you have a group by on the subquery?
Also run explain plan top find out what is taking the time.
This might work better:
( SELECT e.*
FROM event_list AS e
INNER JOIN members AS m ON m.profilenam = e.even_loc
JOIN network AS n ON e.even_own = n.frd_id
WHERE n.mem_id = '911'
AND e.even_active = 'y'
ORDER BY e.even_stat ASC )
UNION DISTINCT
( SELECT e.*
FROM event_list AS e
INNER JOIN members AS m ON m.profilenam = e.even_loc
WHERE e.even_own = '911'
AND e.even_active = 'y' )
ORDER BY e.even_stat ASC
Since I don't know whether the JOINs one-to-many (or what), I threw in DISTINCT to avoid dups. There may be a better way, or it may be unnecessary (that is, UNION ALL).
Notice how I avoid two things that are performance killers:
OR -- turned into UNION
IN (SELECT...) -- turned into JOIN.
I made aliases to cut down on the clutter. I moved the ORDER BY outside the UNION (and added parens to make it work right).

MAX() Function not working as expected

I've created sqlfiddle to try and get my head around this http://sqlfiddle.com/#!2/21e72/1
In the query, I have put a max() on the compiled_date column but the recommendation column is still coming through incorrect - I'm assuming that a select statement will need to be inserted on line 3 somehow?
I've tried the examples provided by the commenters below but I think I just need to understand this from a basic query to begin with.
As others have pointed out, the issue is that some of the select columns are neither aggregated nor used in the group by clause. Most DBMSs won't allow this at all, but MySQL is a little relaxed on some of the standards...
So, you need to first find the max(compiled_date) for each case, then find the recommendation that goes with it.
select r.case_number, r.compiled_date, r.recommendation
from reporting r
join (
SELECT case_number, max(compiled_date) as lastDate
from reporting
group by case_number
) s on r.case_number=s.case_number
and r.compiled_date=s.lastDate
Thank you for providing sqlFiddle. But only reporting data is given. we highly appreciate if you give us sample data of whole tables.
Anyway, Could you try this?
SELECT
`case`.number,
staff.staff_name AS ``case` owner`,
client.client_name,
`case`.address,
x.mx_date,
report.recommendation
FROM
`case` INNER JOIN (
SELECT case_number, MAX(compiled_date) as mx_date
FROM report
GROUP BY case_number
) x ON x.case_number = `case`.number
INNER JOIN report ON x.case_number = report.case_number AND report.compiled_date = x.mx_date
INNER JOIN client ON `case`.client_number = client.client_number
INNER JOIN staff ON `case`.staff_number = staff.staff_number
WHERE
`case`.active = 1
AND staff.staff_name = 'bob'
ORDER BY
`case`.number ASC;
Check below query:
SELECT c.number, s.staff_name AS `case owner`, cl.client_name,
c.address, MAX(r.compiled_date), r.recommendation
FROM case c
INNER JOIN (SELECT r.case_number, r.compiled_date, r.recommendation
FROM report r ORDER BY r.case_number, r.compiled_date DESC
) r ON r.case_number = c.number
INNER JOIN client cl ON c.client_number = cl.client_number
INNER JOIN staff s ON c.staff_number = s.staff_number
WHERE c.active = 1 AND s.staff_name = 'bob'
GROUP BY c.number
ORDER BY c.number ASC
SELECT
case.number,
staff.staff_name AS `case owner`,
client.client_name,
case.address,
(select MAX(compiled_date)from report where case_number=case.number),
report.recommendation
FROM
case
INNER JOIN report ON report.case_number = case.number
INNER JOIN client ON case.client_number = client.client_number
INNER JOIN staff ON case.staff_number = staff.staff_number
WHERE
case.active = 1 AND
staff.staff_name = 'bob'
GROUP BY
case.number
ORDER BY
case.number ASC
try this

MySQL Update with Subquery

I've got an annoying issue with an update query I'm trying to get working... The following statement SHOULD update channels.media_view_count to the result of the subquery (for all channels).
UPDATE channels c
SET c.media_view_count = (
SELECT SUM(t.view_count)
FROM (
SELECT DISTINCT m.viewkey, m.view_count
FROM media m
INNER JOIN participants p ON m.id = p.medium_id
WHERE p.user_id = c.id AND m.is_viewable = 1
AND (p.pending = 0)
) AS t
);
The subquery works fine independently (when specifying an actual id for c.id, like 47778 or whatever), but when I execute this statement, I get:
ERROR 1054 (42S22): Unknown column 'c.id' in 'where clause'
I thought I would be able to access the channels table (aliased as c) from within the subquery? Am I missing something or am I totally wrong here?
Any and all help is appreciated :)
Thanks,
Jeff
UPDATE channels c, (
SELECT t.user_id, SUM(t.view_count) cnt
FROM (
SELECT DISTINCT p.user_id, m.viewkey, m.view_count
FROM media m
INNER JOIN participants p ON m.id = p.medium_id
WHERE m.is_viewable = 1
AND (p.pending = 0)
) AS t GROUP BY t.user_id ) temp
SET c.media_view_count = temp.cnt
WHERE c.id = temp.user_id
Try like this... Did not test it though :) ..
Conceptually, it should work