With MySQL, how can I insert into a table, provided that this value does not exist in another table?

I have a MySQL database, and I would like to insert some values ​​into one table, assuming that the specific value that I insert does not match the value in another table.

Here is a simplified / sample structure:

Table: invites
    id : int (auto-increment index)
    name : varchar
    message : varchar

Table: donotinvite
    name : varchar (index)

Is it possible to conditionally insert a pair of “name” and “message” into the “invites” table if the “name” does not match any “name” from the “donotinvite” table with one expression?

Something like this, maybe?

INSERT INTO invites
    SET name = 'joe', message = 'This is an invite'
WHERE NOT EXISTS 
    (SELECT name 
    FROM donotinvite
    WHERE name = 'joe')
+3
source share
5 answers
INSERT
INTO invites (name, message)
SELECT a.name, a.message
FROM (SELECT @name AS name, @message AS message) a
LEFT JOIN donotinvite d
ON a.name = d.name
WHERE d.name IS NULL
+4
source

( MSSQL, , MySQL)

INSERT INTO invites
(
    name, message
)
SELECT name = 'joe', message = 'This is an invite'
WHERE NOT EXISTS 
    (SELECT *
    FROM donotinvite
    WHERE name = 'joe')

/ , :

INSERT INTO invites
(
    name, message
)
SELECT T.name, T.message
FROM MyTempTable AS T
WHERE NOT EXISTS 
(
    SELECT *
    FROM donotinvite AS DNI
    WHERE DNI.name = T.name
)
+3

, , . :

INSERT INTO invites(name, message) 
SELECT p.name, "This is an invite" 
FROM people AS p  
WHERE p.name NOT IN (SELECT name FROM donotinvite);

people, , ?

+2
INSERT INTO invites (name, message) 
SELECT 'joe', 'This is an invite' FROM (SELECT 1) t 
WHERE NOT EXISTS (SELECT * FROM donotinvite WHERE name = 'joe');
+2

jonstjohn , :

INSERT INTO invites (name, message) 
    SELECT 'joe','This is an invite' 
    FROM donotinvite 
    WHERE name <> 'joe'

EDIT: , :).

+1

Source: https://habr.com/ru/post/1703303/


All Articles