Database INSERT INTO SET ... WHERE(SELECT ...)

969 Views Asked by At

I am trying to insert my values into table if Admin_User_Role_Id value against Admin_Id is not present in the table. Is it possible to insert!

My Table Structure:

Admin_User_Id (FK)
Admin_User_Role_Id (FK)
Is_Enabled (boolean flag)

Query which I tried, but not success

INSERT INTO role_association 
SET Admin_User_Id=61, Admin_User_Role_Id=2, Is_Enabled=0 
WHERE Admin_User_Role_Id 
NOT IN 
(SELECT Admin_User_Id, Admin_User_Role_Id FROM role_association)

I think it is possible but my logic is wrong. How should I manage this query to work successfully!

2

There are 2 best solutions below

0
On

INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.

Probably you take care about where condition in your programming logic and write a simple insert statement and the depending on your logic use this statement to insert the records. Hope you got my point.

1
On

You want to insert your values in your table using this query for your reference

INSERT INTO Yourtablename(column1,column2,column3,...) VALUES ('value1','value2','value3',.....);

You want to ADD one new column in your table means using this query

** ALTER TABLE table_name ADD column_name datatype**