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

Time:01-27

I have table like that:

Table example

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.

CodePudding user response:

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;

CodePudding user response:

If i understand you correctly, this should be what you looking for.

INSERT INTO 
    document_category(document_id, category_id, is_main_category)
SELECT 
    210, 181, 0
FROM 
    dual
WHERE
    (SELECT COUNT(1) FROM documents WHERE document_id = 210) < 2;
  • Related