insert if row do not exists else update row - mysql

I have auto incremented field in votes table where user can up-vote and down-vote on a post. If a user request to up-vote on the post, I want to check the table to see if they have already voted(down or up).
if the user already down-vote and a record is inserted and this time he wants to change to up-vote: I just want to update the record and set vote status to 1, likewise If user request to down-vote and a record is inserted by the same user then just update record and set column status to 0.
I wrote an SQL to do this job but it gives me error under network console :
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE votes VT SET
VT.vote_status = '1',
VT.vote_time='1583319756' ' at line 8
I have search couple of examples but it doesn't see to work. I do not want to use sql ON DUPLICATE KEY I have read it only for the duplicate unique key.
I want to check if 2 or 3 columns is the same as the record I want to insert exist, then update else insert.
How do I achieve this?
my code:
IF EXISTS (
SELECT * FROM $votes_table VT WHERE VT.vote_ask_id='{$Qid}'
AND VT.vote_type='{$vote_type}'
AND VT.vote_status='{$vote_down_status}'
AND VT.vote_user_id='{$CUid}'
)
UPDATE $votes_table VT SET
VT.vote_status = '{$vote_up_status}',
VT.vote_time='{$current_time}'
WHERE VT.vote_user_id = '{$CUid}'
AND VT.vote_ask_id = '{$Qid}'
ELSE INSERT INTO $votes_table(vote_ask_id,vote_type,vote_status,vote_user_id,vote_time)
VALUES('{$Qid}','{$vote_type}','{$vote_up_status}','{$CUid}','{$current_time}')

I recommend you change function update and insert.
You can use "Merge into "

Related

A variable is cut in a wrong way but now sure why?

I'm writing a script that locates all branches of a specific repo that haven't received any commits for more than 6 months and deletes them (after notifying committers).
This script will run from Jenkins every week, will store all these branches in some MySQL database and then in the next run (after 1 week), will pull the relevant branch names from the database and will delete them.
I want to make sure that if for some reason the script is run twice on the same day, relevant branches will not get added again to the database, so I check it using a SQL query:
def insert_data(branch_name):
try:
connection = mysql.connector.connect(user=db_user,
host=db_host,
database=db_name,
passwd=db_pass)
cursor = connection.cursor(buffered=True)
insert_query = """insert into {0}
(
branch_name
)
VALUES
(
\"{1}\"
) where not exists (select 1 from {0} where branch_name = \"{1}\" and deletion_date is NULL) ;""".format(
db_table,
branch_name
)
cursor.execute(insert_query, multi=True)
connection.commit()
except Exception as ex:
print(ex)
finally:
cursor.close()
connection.close()
When I run the script, for some reason, the branch_name variable is cut in the middle and then the query that checks if the branch name already exists in the database fails:
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 not exists (select 1 from branches_to_delete where branch_name = `AUT-1868' at line 8
So instead of checking for 'AUT-18681_designer_create_new_name_if_illegal_char_exist' it checks for 'AUT-1868' which doesn't exist in the database.
I've tried the following:
'{1}'
"{1}"
{1}
But to no avail.
What am I doing wrong?
Using WHERE statement in INSERT INTO query is illegal:
INSERT INTO `some_table`(`some_column`)
VALUES ('some_value') WHERE [some_condition]
So, the above example is not valid MySQL query. For prevent duplication of branch_name you should add unique index on your table like:
ALTER TABLE `table` ADD UNIQUE INDEX `unique_branch_name` (`branch_name`);
And after this you can use next query:
INSERT INTO `table` (`branch_name`) VALUES ('branch_name_1')
ON DUPLICATE KEY UPDATE `branch_name` = `branch_name`;
Pay attention: If your table have auto-increment id, it will be incremented on each insert attempt
Since MySQL 8.0 you can use JASON_TABLE function for generate pseudo table from your values filter it from already exists values and use it fro insert. Look here for example
I don't see anything wrong assuming the source of the branch_name is safe (you are not open to SQL Injection attacks), but as an experiment you might try:
insert_query = f"""insert into {db_table}(branch_name) VALUES(%s) where not exists
(select 1 from {db_table} where branch_name = %s and deletion_date is NULL)"""
cursor.execute(insert_query, (branch_name, branch_name))
I am using a prepared statement (which is also SQL Injection-attack safe) and thus passing the branch_name as a parameters to the execute method and have also removed the multi=True parameter.
Update
I feel like a bit of a dummy for missing what is clearly an illegal WHERE clause. Nevertheless, the rest of the answer suggesting the use of a prepared statement is advice worth following, so I will keep this posted.

SQL: Unrecongnized statement near conditional (IF)

I've never used IF's before in SQL. I need to update a row where institution is a specific number if it exists and insert it if it doesn't. In order to avoid using first a select and then a insert or update I wanted to try my hand at an IF statement. I figured from what I've read in the documentation that it should go something like this:
IF (NOT EXISTS(SELECT evaluations FROM tEvaluations WHERE institution = 0))
BEGIN
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
END
ELSE
BEGIN
UPDATE tEvaluations SET evaluations = 10 WHERE institution = 0
END
However I get this error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'BEGIN
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
END' at line 2
I'm trying to run this query in phpmyadmin to test out how the query should be.
You can't have if..else block in normal SQL statement unless it's inside a procedural block. To me looks like you are looking for INSERT ON DUPLICATE KEY UPDATE like
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
ON DUPLICATE KEY UPDATE evaluations = 10;
Per documentation, either of your column should have a UNIQUE constraint defined against it. Quoting from documentation
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be
inserted would cause a duplicate value in a UNIQUE index or PRIMARY
KEY, an UPDATE of the old row occurs. For example, if column a is
declared as UNIQUE and contains the value 1

Syntax Error in MYSQL clausules

Hello stackoverflow's friends i need your help with this sql clausule this is the error into mysql:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE email='Tysaic0344#gmail.com'' at line 1")
and this is my code:
INSERT INTO user (token) VALUES (1) WHERE email='example#email.com'
You cannot insert values into an existing row. You can either update or delete the existing records. In your case, I think you want to update the existing row. You can use UPDATE.
UPDATE user SET token = 1 WHERE email = 'example#email.com';
If you want to add records to the table use INSERT
INSERT INTO user VALUES (1, 'example#email.com');
Here is the link for your reference
https://msdn.microsoft.com/en-us/library/bb243852(v=office.12).aspx
You can't INSERT with a WHERE clause.
If you need to UPDATE the record where you have the email from:
UPDATE user
Set token = 1
WHERE email='example#email.com'
Or INSERT with email
INSERT INTO user (token, email)
VALUES (1, 'example#email.com')
(or without)
INSERT INTO user (token)
VALUES (1)
These kind of errors you MUST be able to fix by yourself, the error even tells you where it went wrong (at the end it says "near 'WHERE...").
Check the docs that dns_nx included (especially https://dev.mysql.com/doc/refman/5.7/en/update.html ) for the correct syntax to do an update.
You cannot INSERT a value into an existing row. The WHERE clause is invalid with INSERT. If you want to update an existing row, then you have to UPDATE the field like this:
UPDATE
user
SET
token = 1
WHERE
email='example#email.com'
Please review the docs about INSERT and UPDATE
https://dev.mysql.com/doc/refman/5.7/en/update.html
https://dev.mysql.com/doc/refman/5.7/en/insert.html
INSERT inserts new rows into a table. The WHERE clause is used to filter existing rows from a table. It doesn't make sense in a INSERT query; that's why the INSERT statement does not contain a WHERE clause.
The WHERE clause is used to filter the rows to fetch from the table (the SELECT statement), the rows to modify (the UPDATE statement) or to remove from the table (the DELETE statement).
Your query looks like you want to modify the data already existing in the table. The UPDATE statement you need looks like this:
UPDATE user SET token = 1 WHERE email = 'example#email.com'

INSERT WHERE EXISTS

For MySQL, If I stored the userid and a token in the user table and only allows to insert record in another table if the supplied userid and token matches.I've tried
INSERT INTO product(description)
VALUES('123')
WHERE EXISTS
(SELECT 1 FROM users where userid='myuserid' AND token='ABCD')
The following SQL statement produces error
"check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE EXISTS (SELECT 1 FROM users where userid='29')'"
However for update I can update successfully with
UPDATE product
SET description='123'
WHERE EXISTS
(SELECT 1 FROM users where userid='myuserid' AND token='ABCD')
Can any experts please help to advise.
I need the most efficient way to verify the user token is correct before doing the insert.
Please try using a trigger instead:
CREATE TRIGGER tokenValidator
BEFORE INSERT
ON product
FOR EACH ROW BEGIN
IF (SELECT 1 FROM users where userid='myuserid' AND token='ABCD') THEN
INSERT INTO product(description) VALUES('123')
END IF

mysql if exists giving error wrong syntax?

I am trying to use IF EXISTS in MySQL but i keep getting syntax errors and I have researched for correct syntax but everything isnt working...
What i need is:
If query exists then UPDATE else INSERT new...
$queryString = "IF EXISTS (SELECT * FROM $ONCALL_TABLE WHERE uid='$contextUser' AND submitid='$submitid' AND submitstatus=3) THEN UPDATE $ONCALL_TABLE SET uid='$contextUser', start_time='$onStr', end_time='$offStr', amount='$amount' ELSE INSERT INTO $ONCALL_TABLE (uid, start_time, end_time, amount) VALUES ('$contextUser','$onStr', '$offStr', '$amount') END IF";
Error message:
Can't perform query: 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 'IF EXISTS (SELECT * FROM timesheet_oncall WHERE uid='admin' AND submitid='136545' at line 1
REPLACE INTO is what you need. http://dev.mysql.com/doc/refman/5.0/en/replace.html
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
In your case
REPLACE INTO
$ONCALL_TABLE (uid, start_time, end_time, amount)
VALUES ('$contextUser','$onStr', '$offStr', '$amount')
WHERE uid='$contextUser';
Assuming uid is a PRIMARY KEY or UNIQUE KEY
NOTE: Since the code in your question contains SQL injection flaws I would recommend you to read this article. http://php.net/manual/en/security.database.sql-injection.php