简体   繁体   中英

MySql - if there is no record, insert multiple rows

Before asking this question, I already search a lot of entries on Google and StockOverflow. Nothing can fulfil my question.

There are two tables - group_sale_bonuses and members . I want to check is already there records with product_id "1" in the group_sale_bonuses .

If not, I want to insert all records from members table into group_sale_bonuses with product_id "1" .

My overall requirement is as follow:

IF ((Select count(id) from group_sale_bonuses where product_id = 1) = 0) THEN
    INSERT INTO group_sale_bonuses (member_id, product_id, quantity_counter, credit)  
    SELECT id, 1, 0, 0 FROM members
END IF

But this sql causes the errors.

I know there are solutions about Insert Ignore , Where Not Exists .

But these conditions checking are based on per each record. I have thousands of records in members table. I want to make condition checking just one time like in my above sql example.

By the way, I will use this Sql in Php web application.

You could just set the code in a WHERE clause instead of the IF .

INSERT INTO group_sale_bonuses(
    member_id, 
    product_id,
    quantity_counter,
    credit) 
SELECT 
    id, 1, 0, 0 FROM members 
WHERE( 
    SELECT 
        count(id) FROM group_sale_bonuses
    WHERE product_id = 1
) = 0;

This should do it for all product_id's

SELECT m.product_id, m.member_id FROM members AS m 
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL ;

You can filter it to a specific product_id by adding to the where clause

SELECT m.product_id, m.member_id FROM members AS m 
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL AND m.product_id = 1;

Take a look at this SQLfiddle: http://sqlfiddle.com/#!2/8482c/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