This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to add a where clause in a MySQL Insert statement?
I am writing a SQL INSERT STATEMENT with WHERE clause.
INSERT INTO House ( ID ,ADDRESS ) VALUES ('12','LONDON') WHERE OWNER='1';
Error i get :
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE OWNER='1'' at line 1
WHERE is used in UPDATE query. Use UPDATE for your query if got where clause.
You can't use WHERE clause with INSERT Query..
If you want update the record already if the record exist
INSERT INTO House ( OWNER, ID ,ADDRESS ) VALUES ('1', '12','LONDON')
ON DUPLICATE KEY UPDATE ID = '12', ADDRESS = 'LONDON'
The 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns
check this link for more info
INSERT INTO doesn't have a WHERE clause. Remove it.
You can onlu use the WHERE clause if you are selecting from a table, or updateing a table.
So you wouls typically have something like
INSERT INTO Table (Columns...) SELECT Columns... FROM SomeOtherTable WHERE Condition
In your case you need to use
INSERT INTO House ( ID ,ADDRESS ) VALUES ('12','LONDON')
WHERE clause doesnot work with INSERT INTO statement. You can use the clause with a SELECT statement
The correct code for you will be as:
INSERT INTO House(ID,ADDRESS) values(12,'LONDON');
Related
Clearly the following is incorrect.
INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name');
I get the value:
SQL query:
INSERT INTO `aTable` (`A`, `B` )
VALUES
(
(
SELECT MAX(`A`)
FROM `aTable`
) *2
, 'name'
)
MySQL said:
1093 - You can't specify target table 'aTable' for update in FROM clause
So, I'm trying to make a bitmap table, each row corresponds to one Bit, and has a 'map' value.
To insert in the table, I don't want to do two queries, I want to do one.
How should I do this?
No one commented on this, but since I am trying to make a bitmap, it should be * 2 not ^ 2, my mistake, please note that is why the comments often say ^ 2, it was an error in the version that the commenters read.
try:
insert into aTable select max(a)^2, 'name' from aTable;
or
insert into aTable select max(a)^2, 'name' from aTable group by B;
If you need a join, you can do this:
insert into aTable select max(a)^2, 'name' from aTable, bTable;
My "Server version" is "5.0.51b-community-nt MySQL Community Edition (GPL)"
Actually, you can alias the table on the insert. I've seen this question all over the place, but no one seems to have tried that. Use a subquery to get the max from the table, but alias the table in the subquery.
INSERT INTO tableA SET fieldA = (SELECT max(x.fieldA) FROM tableA x)+1;
A more complex example, where you have a corresponding secondary key and might be inserting the FIRST record for the corresponding secondary key:
INSERT INTO tableA SET secondaryKey = 123, fieldA = COALESCE((SELECT max(x.fieldA) FROM tableA x WHERE x.secondaryKey = 123)+1,1);
By aliasing the table, it doesn't throw the error and seems to work. I just did this while coding something, although I can't see if there area any silly syntax errors above, I would try that type of syntax.
I take it that INSERT ... SELECT isn't working? I see this in the documentation for it:
The target table of the INSERT
statement may appear in the FROM
clause of the SELECT part of the
query. (This was not possible in some
older versions of MySQL.) In this
case, MySQL creates a temporary table
to hold the rows from the SELECT and
then inserts those rows into the
target table.
Out of curiosity, which version of MySQL are you using?
I think you need to drop the "VALUES", and have a valid select statement.
see this link
I'm not particularly a mySQL guy, I use MSSQL mostly. But If you format the select statement correctly, It should work.
as soon as the Select is correct you can do this.
So i am trying to follow this tutorial
Insted of doing a query like this ("Which i could not get to work either...")
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
I want to do it like this
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF ##ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
The benefit of doing it like this should be to avoid two index searches.
Table
SQL
UPDATE ctc_portfolio_coins SET (ctc_portfolio_coins_amount = 100) WHERE ctc_portfolio_coins_portfolio_fk = 1
IF ##ROWCOUNT=0
INSERT INTO ctc_portfolio_coins (ctc_portfolio_coins_portfolio_fk, ctc_portfolio_coins_coin_fk, ctc_portfolio_coins_amount) VALUES (1, 1, 100)
Error
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(ctc_portfolio_coins_amount = 100) WHERE ctc_portfolio_coins_portfolio_fk=1
IF ' at line 1
Can anyone tell me what is goin on and maybe tell me what i did wrong?
The correct way to implement the original query in MySQL is to use ON DUPLICATE KEY UPDATE along with a unique index:
CREATE UNIQUE INDEX idx_table1_column1 ON table1(column1);
INSERT INTO table1(col1, . . . )
VALUES ( . . . )
ON DUPLICATE KEY UPDATE col1 = VALUES(col1), . . .;
You should not be learning the IF EXISTS formulation. It is inferior due to race conditions -- two threads attempting similar operations at the same time.
For your particular query, ##ROWCOUNT is not part of MySQL. You query would be phrased as:
INSERT INTO ctc_portfolio_coins (ctc_portfolio_coins_portfolio_fk, ctc_portfolio_coins_coin_fk, ctc_portfolio_coins_amount)
VALUES (1, 1, 100)
ON DUPLICATE KEY UPDATE ctc_portfolio_coins_amount = VALUES(ctc_portfolio_coins_amount);
This assumes that you have a unique index on the column that you do not want duplicated.
So my table looks like this (from the "Show Create Table <table>" query) :
CREATE TABLE stars_in_movies(
star_id int NOT NULL,
movie_id int NOT NULL,
KEY 'star_id' ('star_id'),
KEY 'movie_id' ('movie_id'),
CONSTRAINT 'stars_in_movies_ibfk_1' FOREIGN KEY('star_id') REFERENCES 'stars'('id'),
CONSTRAINT 'stars_in_movies_ibfk_2' FOREIGN KEY('movie_id') REFERENCES 'movies'('id'),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
And I am trying to simply enter a new entry into this table as so:
INSERT INTO stars_in_movies (907010, 834410);
And I get an Error as follows:
ERROR 1064 (4200): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to user near '907010, 834410)' at line 1
Now I know that this error is just simply a syntax error, but why am I receiving the error for such a simple INSERT query? Everywhere online suggest that this would be a valid statement, especially if the two entry fields are ACTUAL ids from the other two referenced tables.
EDIT:
Okay so for this trivial example I was simply missing the VALUES keyword. To add onto the question, how come this query returns the same error?
INSERT INTO stars_in_movies
VALUES
(693109, m.id)
SELECT m.id
FROM movies m
WHERE m.title='Inception';
Seems like you are missing the VALUES keyword.
INSERT INTO stars_in_movies (star_id, movie_id) VALUES (907010, 834410)
^^^^^^
Try this:
INSERT INTO stars_in_movies values (907010, 834410);
You are missing the keyword values.
SQL FIDDLE DEMO
EDIT:
After you comment, you also have one more option to insert into the table like this
INSERT INTO stars_in_movies
select 907010, 834410;
EDIT:
This query wont work
INSERT INTO stars_in_movies
VALUES
(693109, m.id)
SELECT m.id
FROM movies m
WHERE m.title='Inception';
You need to specify the particular value in the VALUES. In
INSERT INTO stars_in_movies
VALUES
(693109, m.id)
m.id is not defined and hence it is unknown to the analyzer. So you are getting the error.
You are probably looking for this:
INSERT INTO stars_in_movies
SELECT 693109, m.id
FROM movies m
WHERE m.title='Inception';
I have a need to do an insert to MySQL where a record does not exist in the destination table already
my query
INSERT INTO comment (`mid`, `pid`, `comment_text`, `comment_date`, `comment_type`)
VALUES (180, 2, NULL, '2012-07-26 10:19:00', 'tag') WHERE NOT EXISTS ( SELECT * FROM `comment` WHERE `mid`=180 AND `pid`=2 AND `comment_type`='tag')
however when this runs I get this error
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'WHERE NOT EXISTS ( SELECT * FROM comment WHERE mid=180 AND
`pid' at line 2
Any ideas essentially i want to stop duplicate rows being added to this table when they match the values
try:
INSERT IGNORE INTO comment
(
`mid`, `pid`, `comment_text`, `comment_date`, `comment_type`
)
(
SELECT 180, 2, NULL, '2012-07-26 10:19:00', 'tag'
FROM comment
WHERE `mid`=180 AND
`pid`=2 AND
`comment_type`='tag'
LIMIT 1
);
EDIT: Better way to do this:
to remove duplicates from a table see here
ALTER IGNORE TABLE comment ADD UNIQUE KEY ix1(mid, pid, comment_type);
INSERT IGNORE INTO comment
(
`mid`, `pid`, `comment_text`, `comment_date`, `comment_type`
)
VALUES
(
SELECT 180, 2, NULL, '2012-07-26 10:19:00', 'tag'
);
Why not just to make unique index that consists of mid, pid and comment_type columns?
add an ignore
INSERT IGNORE INTO comment ...
to prevent duplicate inserts. You can't use a where clause in an insert.
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.
Taken from the MySQL INSERT Documentation
That means you should add a unique key to your table (if you haven't already) to make the DB check for duplicates by itself. If the DB finds a duplicate no INSERT will be made.
if you want to make an UPDATE in case of duplicates that is possible too. See here
Trying to duplicate some rows in a table but just change the ssreportid column from 4 to 6:
INSERT INTO ssreportparticipant (ssreportid, sssurveyparticipantid)
VALUES
SELECT 6, sssurveyparticipantid FROM ssreportparticipant
WHERE ssreportid = 4
The error says #1064 near 'select 6, ...' but if I just run the select clause, it selects the records perfectly, with the new id of 6 in the ssreportid column.
The table has a primary key called ssreportparticipantid, and there is a unique key on (ssreportid, sssurveyparticipantid). Note that the select clause creates new records that have unique key pairs, so that's not the problem. I have tried putting brackets around the select clause, and even using two aliases for the table, no joy.
Using server version 5.0.45.
Please tell me that programmer fatigue has me missing a comma or something.
Thanks,
-Josh
I think you should remove "VALUES"
I am not sure, but maybe it is possible that you cannot insert into a table with a select from the same table. Have you tried to select from a different table, just for the sake of testing ?