This doesn't work:
INSERT INTO users (username, password) VALUES ("Jack","123") WHERE id='1';
Any ideas how to narrow insertion to a particular row by id?
Copying specific rows from a table: We can copy specific rows from a table to insert into another table by using WHERE clause with the SELECT statement. We have to provide appropriate condition in the WHERE clause to select specific rows.
With the help of same structure table. If we want to insert in a table whose structure is same as another table then in the following example it has been demonstrated that how we can have conditional insert i.e. how we can use WHERE clause with INSERT INTO statement.
You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.
To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP.
A conditional insert for use typically in a MySQL script would be:
insert into t1(col1,col2,col3,...)
select val1,val2,val3,...
from dual
where [conditional predicate];
You need to use dummy table dual.
In this example, only the second insert-statement will actually insert data into the table:
create table t1(col1 int);
insert into t1(col1) select 1 from dual where 1=0;
insert into t1(col1) select 2 from dual where 1=1;
select * from t1;
+------+
| col1 |
+------+
| 2 |
+------+
1 row in set (0.00 sec)
In an insert statement you wouldn't have an existing row to do a where claues on? You are inserting a new row, did you mean to do an update statment?
update users set username='JACK' and password='123' WHERE id='1';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With