Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Update with left join and group by having

I'm making an update to our database and would like to update rows that do not have existing items in another table. I can join the tables together, but am having trouble grouping the table to get a count of the number of rows

UPDATE dpt
SET dpt.active = 0 
FROM DEPARTMENT dpt
LEFT JOIN DOCUMENTS doc on dpt.ID = doc.DepartmentID
GROUP BY dpt.ID
HAVING COUNT(doc.ID) = 0

What should I be doing?

like image 942
Marty Trenouth Avatar asked Jan 22 '23 10:01

Marty Trenouth


2 Answers

Use:

UPDATE DEPARTMENT
   SET active = 0 
 WHERE NOT EXISTS(SELECT NULL 
                    FROM DOCUMENTS doc
                   WHERE doc.departmentid = id)
like image 169
OMG Ponies Avatar answered Jan 28 '23 11:01

OMG Ponies


UPDATE  department
SET     active = 0
WHERE   id NOT IN
        (
        SELECT  departmentId
        FROM    doc
        )
like image 41
Quassnoi Avatar answered Jan 28 '23 13:01

Quassnoi