简体   繁体   中英

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

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.

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM