MySQL Error, specifically an If Exist statement [duplicate] - mysql

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 6 years ago.
I tried using from mySQL the If Exists statement but i got an error from mysql saying there's a #1064 syntax error, but i really couldn't find it. There are my codes:
If EXISTS (select * from points where username= 'john')
update points set points = "4" where username='john'
ELSE
insert into points (username, points) values ('john', 5);

You have a syntax error in your statement. You are missing "THEN" keyword after EXISTS and "END IF" at the end, and also missing a semicolon on UPDATE statement. If you still want to go with this statement, it should be like this:
IF EXISTS (select * from points where username= 'john') THEN
UPDATE points set points = "4" where username = 'john';
ELSE
INSERT into points (username, points) values ('john', 5);
END IF;
Please take a note that this statement can be only used in routine such as Stored Procedure or Stored Function and not in normal SQL.
On the other hand, what #TimBiegeleisen said in his answer is a more efficient way to go.

One way to achieve your logic would be to use ON DUPLICATE KEY UPDATE while doing your INSERT:
INSERT INTO points (username, points)
VALUES ('john', 5)
ON DUPLICATE KEY UPDATE points=4
This query will insert ('john', 5') into your table, but if the primary key username john already exists, then it will points to 4.

Related

PDO insert max id+1 not auto_increment

I don't want to use auto increment of mysql ,But I want to get max id+1 to insert as ID for next data.
I tried to do as How to get auto increment id by PDO before execute
But no luck.
$sql = "INSERT INTO checklist ((SELECT MAX(checklist_id)+1), checklist_name ) VALUES (NULL, :checklist_name)";
$pdo_statement = $pdo_conn->prepare( $sql );
$result = $pdo_statement->execute ((array(':maxid'=>NULL,':checklist_name'=>$_POST['checklist_name']));
Could you please help me what code it should be?
Edit: as one of the commentors have pointed out above; it is not recommended to not have PRIMARY Key in your MySQL Database
Your SQL query is wrong. You need to have columns and values separately.
$sql = "INSERT INTO checklist ((SELECT MAX(checklist_id)+1), checklist_name ) VALUES (NULL, :checklist_name)";
To make your INSERT statement correct look at the documentation
INSERT INTO table (column, column, etc.) VALUES (value, value, etc.)
So to make your statement correct you will have to switch some of the variables
INSERT INTO checklist (checklist_id, checklist_name) VALUES ((SELECT MAX(checklist_id)+1 FROM checklist), :checklist_name)
And your array with your bind values will look like this
array(':checklist_name' => $_POST['checklist_name'])
If you have problems with any SQL syntax you can look at the documentation or w3schools tutorials.

SQL Error when trying to insert one value into one row for a column

I'm using MySQL 5.7 and for some reason my INSERT statement isn't working as before even though the syntax looks correct. It's error-ing out on the where statement...
SQL:
insert into users(age) values('16') where username='r';
If the row for username r already exists perhaps you are looking to update the age value instead?
Use: update users set age = 16 where username = 'r' instead.
Also, I'm just guessing here, but maybe age holds a numeric value, and if so you can remove the quotes around 16.
That syntax isn't correct. You can't use where like that. Perhaps you want something like:
insert into users (username, age)
values ('r', '16')
http://dev.mysql.com/doc/refman/5.7/en/insert.html
Alternatively if that user already exists, you might be looking for an update statement instead:
update users set age = '16' where username = 'r'
INSERT statements must not contain a WHERE clause. Remove it.
If, in fact what you are trying to do is update an existing row, use an UPDATE statement, not an INSERT statement.
update users set age = '16' where username='r';
If you want to insert new records in your table, you have to write query for inserting data.
SQL INSERT INTO Statement syntax is this:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
In your case, if you don't have the record in your database, your query will look like this:
INSERT INTO users (username, age)
VALUES ('r', '16')
But if you want to update existing records in your table, you have to write query for updating data using the SQL UPDATE Statement.
The syntax for this is:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
To update the record/s, you have to specify clause in WHERE which record should be modified.
To modify age of user/s with username that is equals 'r', this is the query:
UPDATE users SET age = 16 WHERE username = 'r'
but if you want to modify for all users which usernames starts with 'r':
UPDATE users SET age = 16 WHERE username = 'r%'
I hope this explanation will help you to understand better SQL statements for INSERT new and UPDATE existing records.

"INSERT IF NOT EXISTS", ELSE UPDATE certain columns in MySQL

I'm using MySQL Workbench (6.3) and I'm trying to create a stored procedure with a specific "INSERT IF NOT EXSISTS" but I think I don't do it well. By the way, I did read this topic http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html and tried both examples, it didn't work. Here is the statement :
CREATE DEFINER=`test`#`localhost` PROCEDURE `onPlayerJoin`(
IN uuid CHAR(36),
IN nickname CHAR(16),
IN firstConnection TIMESTAMP,
IN lastConnection TIMESTAMP
)
BEGIN
INSERT IGNORE INTO `test`.`player` (`playerUuid`, `playerNickname`, `playerFirstConnection`, `playerLastConnection`)
VALUES (uuid, nickname, firstConnection, lastConnection);
UPDATE `test`.`player` SET
`playerNickname` = nickname,
`playerLastConnection` = lastConnection
WHERE `playerUuid` = uuid;
END
IF the PK isn't found, INSERT it. ELSE, UPDATE certain columns. (that I can specified) However, it seems that it updates every column, which I would like to restrict to certain columns. Here is my procedure : http://pastebin.com/NfcdU9Rb !
Optional question : is it injection-safe ?
Use INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Kindly refer the link for details:
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

MySQL "insert.... where not exists" is coming up all errors

This works:
insert into answers
(survey,user,answer)
values(1,'hi',1)
;
This works:
select * from answers where survey=1 and user='hi';
This doesn't work:
insert
into answers
(survey,user,answer)
values(1,'hi',1)
where not exists (select * from answers where survey=1 and user='hi')
;
It gives me an error 1064 right around the "where not exists" clause. I've looked up all the documentation I can find, but I can't find anything wrong with it.
Thoughts?
You can do this with insert . . . select, but not insert . . . values:
insert into answers(survey, user, answer)
select survey, user, answer
from (select 1 as survey, 'hi' as user, 1 as answer) s
where not exists (select 1 from answers a where a.survey= s.survey and a.user = s.user);
That said, I would advise you to make answer(survey, user) either a unique or primary key, so the database enforces the uniqueness constraint.
Syntax for the INSERT statement in MySQL (https://dev.mysql.com/doc/refman/5.6/en/insert.html) has no "where not exists".
What you probably want is INSERT IGNORE INTO answers (survey,user,answer) values(1,'hi',1). This inserts the values unless it clashes with a primary or unique key on the table, in which case the values are ignored.
Indeed, the INSERT INTO ... VALUES ... notation doesn't support a WHERE clause. Instead, you need to use the INSERT INTO ... SELECT ... notation, where you specify an actual query to generate the rows to insert. That query can, of course, contain a WHERE clause:
insert
into answers
(survey,user,answer)
select 1,'hi',1
from (select 1)
where not exists (select * from answers where survey=1 and user='hi')
;

Insert new row unless ONE of the values matches another row?

I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)
I want to be able to check to see if any other row in the table already has name = 'Fred'. How can this be done?
Thanks!
EDIT
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
select id from mytable
)
which throws the 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 'WHERE '12gfa' not in ( select id from mytable)' at line 3
First of all, your id field should be an autoincrement, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for id for each row.
If it's not the case, you should create a primary key for the table that includes ALL the fields you don't want to duplicate and use the INSERT IGNORE command.
Here's a good read about what you're trying to achieve.
You could use something like this
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");
This will insert a new row, unless a row already exists with a duplicate key, it will update it.
DELIMITER |
CREATE PROCEDURE tbl_update (IN id INT, IN nm VARCHAR(15))
BEGIN
DECLARE exst INT;
SELECT count(name) INTO exst FROM mytable WHERE name = nm;
IF exst = 0 THEN
INSERT INTO mytable VALUES(id, name);
END IF;
END
|
DELIMITER ;
or just make an attribute name as UNIQUE