Question

I have a series of weblog entries in table exp_weblog_titles t. That are categorized by categories in table exp_categories c and joined by table exp_category_posts cp.

There is a parent child relationship in categories. At this time I would like to take all my entries that are currently categorized with children of category 4810 and categorize those entries themselves with category 4810.

This is the (untested) query I have come up with for this operation:

INSERT INTO exp_category_posts (entry_id,cat_id)
(select distinct(t.entry_id), '4810' 
from
    exp_weblog_titles t
        left join
    exp_category_posts cp ON t.entry_id = cp.entry_id
        left join
    exp_categories c ON c.cat_id = cp.cat_id
where
    t.weblog_id = 5 and c.parent_id = 4810)

But I would like to avoid inserting new join records in category_posts cp where an identical one might exist.

I can't get my head around the WHERE NOT EXISTS. Should it be part of the insert operation, the subselect? Can't figure it either way.

It would be something like:

IF NOT EXISTS 
SELECT * FROM exp_category_posts 
where cat_id = 4810 and entry_id = $thecurrentrow

But do I refer to the current row?

This is in ExpressionEngine 1.

Update arising from Mats's Answer: There is no unique key on (entry_id, cat_id). Not sure of the consequences of adding one.

Was it helpful?

Solution

Assuming that (entry_id, cat_id) is a unique key in exp_category_posts you should be able to use INSERT IGNORE. The INSERT IGNORE will skip records that would generate a duplicate key error when being inserted.

You can find more information in the reference manual http://dev.mysql.com/doc/refman/5.5/en/insert.html.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top