Skip to main content
Inspiring
January 18, 2007
Question

SQL: Updating via joins

I need to update some records in a table based on a query using two joins.

The specific records I need to delete are determined via the query:

SELECT WeFAQs.collectionID, WeFAQs.question, WeFAQs.categoryID,
WeFAQs.publicAccess, WeFAQs.sort
FROM WeFAQs LEFT OUTER JOIN
We_about_categories CAT ON CAT.categoryID =
WeFAQs.categoryID LEFT OUTER JOIN
We_about_categories PARENTCAT ON PARENTCAT.categoryID
= CAT.categoryParentID
WHERE (WeFAQs.categoryID = 9) OR
(categoryParentID = 9)

I only need to update the 5 fields selected in the WeFAQs table.

So, my question...can I do this with a SELECT INTO or an UPDATE command? The
syntax is eluding me.

Or is this a prime example of where a temp table is useful?

-Darrel


This topic is closed to new replies. Start a new post to keep the conversation going.

12 replies

Inspiring
January 18, 2007
You can have syntax like

update a set a.f=b.f
from a inner join b on a.id=b.id

--
Jules
http://www.charon.co.uk/charoncart
Charon Cart 3
Shopping Cart Extension for Dreamweaver MX/MX 2004



Translate
Inspiring
January 18, 2007
It appears you're simply selecting all records from WeFAQs that are in
category 9 or a subcategory of category 9. That doesn't really require two
joins on the categories table.

Anyway, you'll need a subquery. Either IN or EXISTS will work; just see
which one's faster on your particular tables:

UPDATE WeFAQs
SET CollectionID=x, etc...
WHERE CategoryID IN (SELECT CategoryID FROM We_about_categories WHERE
CategoryID=9 OR CategoryParentID=9)

UPDATE WeFAQs
SET CollectionID=x, etc...
WHERE EXISTS(SELECT * FROM We_about_categories WHERE
CategoryID=WeFAQs.CategoryID AND (CategoryID=9 OR ParentCategoryID=9))

I think the IN version is easier to understand this time around and better
describes what you're actually trying to do.


Translate