1

The task is to keep "mg_brands" table updated with values coming from query on another two tables.

Tables are:

mg_brands | mg_term_taxonomy  |mg_terms
----------|-------------------|--------------
term_id   | term_taxonomy_id  |term_id
name      | term_id           |name
          | taxonomies        |

Basically, it works in this way: mg_terms contain records having different categories identified by the "field mg_term_taxonomy.taxonomies".

I would like to extract records having taxonomy "brand" and transfer that data into "mg_brands". The query should be capable of checking existing records updating them or insert new ones if not exist.

For that I am using the below reported query but it create new records, duplicating them instead of doing what I already said.

INSERT into mg_brands

    SELECT mg_terms.term_id,  mg_terms.name
    FROM mg_terms
    JOIN mg_term_taxonomy
    ON mg_term_taxonomy.term_id=mg_terms.term_id
    WHERE mg_term_taxonomy.taxonomy="product_brand"

    ON DUPLICATE KEY UPDATE
    mg_brands.term_id = mg_terms.term_id,
    mg_brands.name= mg_terms.name

Any suggestion why the ON DUPLICATE KEY UPDATE is not doing its work?

Thanks

10
  • What do you mean with "is not doing its work?" Do you get an error? Commented Aug 7, 2017 at 17:03
  • Hi, I mean that instead of checking if the record exists and eventually update the fields, the query add records every time I launch it. I suppose it depends from the bad coding on that part. Commented Aug 7, 2017 at 17:12
  • 1
    A question about ON DUPLICATE KEY that doesn't include the KEYs that the (key)word KEY in that command is referring to (your indexes on that table) is missing a very important part. So please add them (e.g. as output of show create table mg_brands). Commented Aug 7, 2017 at 17:14
  • 1
    @Solarflare, the key is the term_id in the mg_brands. At this point I have no idea how to implement the function I need. Any suggestion? Commented Aug 7, 2017 at 17:18
  • Then as @Solarflare says, you have a problem with your KEY. Are tyou sure it´s a unique KEY?? It looks like don´t Commented Aug 7, 2017 at 17:19

1 Answer 1

1

You need to set the term_id as UNIQUE KEY so the ON DUPLICATE will work. The problem it´s that now you don´t have any duplicate because you don´t have term_id as PRIMARY KEY

Sign up to request clarification or add additional context in comments.

1 Comment

SOLVED - Indeed I was missing the UNIQUE KEY. As I selected it for the term_id, the query worked fine. Thanks for your help!

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.