Search code examples
sqlcountinsert

Insert into table only if select statement shows less than 2 rows


I have table like that:

id document_id category_id is_main_category
1765 210 181 0
1764 210 179 1
1763 201 179 1
1762 209 181 0
1761 209 179 1
1754 211 182 0
1753 211 180 1

I need to select:

SELECT * FROM `documents` WHERE document_id = 210;

And if the number of rows is less than 2 I would like to insert into table one more row, like that:

INSERT INTO document_category (document_id, category_id, is_main_category)
VALUES (210, 181, 0);

Could you please help me to merge those 2 constructions.


Solution

  • Maybe you can build upon this:

    INSERT INTO document_category (document_id, category_id, is_main_category)
    SELECT 210, 181, 0
    FROM documents
    WHERE document_id = 210
    GROUP BY document_id
    HAVING COUNT(*) < 2;