1

I have these 3 tables

Table books (i want to fill categories column with 1 string of categories delimited with a comma)

id      categories
1       null
2       null
3       null
...     ...

Table categories

id      name
1       adventure
2       horror
...     ...

Table BooksCategories (a book can have multiple categories)

bookid    categoryid
1         1
1         3
2         2
3         1
3         2
...       ...  

I have a query that gives me something like this

bookid      categories
1           horror, adventure
2           action,...,...

Now, I want to update the column categories of my books table to the corresponding value of my query. Is it possible to do that in an update?

Thanks, I hope it is clear enough

1
  • 1
    Please re-consider your design: what you want to achieve is a presentation layer that could - and should, in most cases - be computed at runtime, or in specific views. Don't store redundant, consistance-dangerous data: you will then need quite a lot of triggering to keep the "categories" column up do date. Commented Sep 13, 2013 at 13:12

1 Answer 1

4

You can JOIN your query with table books so you can update the column,

UPDATE  a
SET     a.categories = b.categories
FROM    books a
        INNER JOIN
        (
            -- paste your query here
            -- SELECT   bookid, categories,.....
        ) b ON  a.id = b.bookid
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.