I am trying to create an update query and making little progress in getting the right syntax. The following query is working:
SELECT t.Index1, t.Index2, COUNT( m.EventType ) FROM Table t LEFT JOIN MEvents m ON (m.Index1 = t.Index1 AND m.Index2 = t.Index2 AND (m.EventType = 'A' OR m.EventType = 'B') ) WHERE (t.SpecialEventCount IS NULL) GROUP BY t.Index1, t.Index2
It creates a list of triplets Index1,Index2,EventCounts. It only does this for case where t.SpecialEventCount is NULL. The update query I am trying to write should set this SpecialEventCount to that count, i.e. COUNT(m.EventType) in the query above. This number could be 0 or any positive number (hence the left join). Index1 and Index2 together are unique in Table t and they are used to identify events in MEvent.
How do I have to modify the select query to become an update query? I.e. something like
UPDATE Table SET SpecialEventCount=COUNT(m.EventType).....
but I am confused what to put where and have failed with numerous different guesses.
SQL Server UPDATE JOIN syntax To query data from related tables, you often use the join clauses, either inner join or left join. In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update.
As of my knowledge, No you can not directly use GROUP by as you can not use aggregate functions in an UPDATE query.
In MySQL, you can use the JOIN clauses in the UPDATE statement to perform the cross-table update.
The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.
I take it that (Index1, Index2)
is a unique key on Table
, otherwise I would expect the reference to t.SpecialEventCount
to result in an error.
Edited query to use subquery as it didn't work using GROUP BY
UPDATE Table AS t LEFT JOIN ( SELECT Index1, Index2, COUNT(EventType) AS NumEvents FROM MEvents WHERE EventType = 'A' OR EventType = 'B' GROUP BY Index1, Index2 ) AS m ON m.Index1 = t.Index1 AND m.Index2 = t.Index2 SET t.SpecialEventCount = m.NumEvents WHERE t.SpecialEventCount IS NULL
Doing a left join with a subquery will generate a giant temporary table in-memory that will have no indexes.
For updates, try avoiding joins and using correlated subqueries instead:
UPDATE Table AS t SET t.SpecialEventCount = ( SELECT COUNT(m.EventType) FROM MEvents m WHERE m.EventType in ('A','B') AND m.Index1 = t.Index1 AND m.Index2 = t.Index2 ) WHERE t.SpecialEventCount IS NULL
Do some profiling, but this can be significantly faster in some cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With