INSERT WHERE EXISTS - mysql

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

Related

insert if row do not exists else update row

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 "

Using a trigger on a table after any modification to copy affected row into a new table

I would like to create a trigger to this example table when I insert, update or delete any row into the table. I have never worked with triggers before so this will be my first one.
I have this code so far:
DROP TRIGGER auditemployees
CREATE TRIGGER auditemployees AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_trigger select * from employees where emp_no = NEW.emp_no;
END;
The problem now is:
I would like to copy the affected row into another table in this case employees_trigger, but in order to copy the whole row and to pass the values all I can think of is using variables for each field which in my opinion sounds inefficient since if I had 50 fields I will have to use 50 variables and then insert all those values into the new table.
Is there any better and efficient way to do this?
Also I get the error:
> 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 'CREATE TRIGGER auditemployees AFTER INSERT ON
> employees
Every statement needs to be terminated -- there is no ; at the end of the DROP statement.
You are missing a DELIMITER statement, and you are not using a different delimiter for the CREATE.
What's wrong with OLD.* for the 50 variables?

MySQL syntax error regarding WHERE NOT EXISTS

I have a Chef recipe for creating Unix user IDs and deploying them across multiple nodes, to guarantee uniqueness and prevent devs from having to track them themselves. They merely name the application and it is granted a unique ID if an ID for that application doesn't already exist. If one does, it is simply returned to the script and user accounts are created on the webservers with the appropriate value.
I have a mysql database with a single table, called application_id_table which has two columns, id and application_name. id is autoincrementing and application name cannot be null (and must be unique).
Removing the Ruby from my script and making a couple of substitutions, my sql looks like this:
INSERT INTO application_id_table(application_name) VALUES('andy_test')
WHERE NOT EXISTS (select 1 from application_id_table WHERE
application_name = 'andy_test');
when run, I receive the syntax parsing error:
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 NOT EXISTS (select 1 from
application_id_table WHERE application_name = 'a'
I recall seeing that the values statement does not allow a where clause but I don't wish to use a select statement to populate the values as I'm populating them from variables supplied from within Ruby/Chef. Anyone have an idea how to accomplish this?
You want to use insert . . . select:
INSERT INTO application_id_table(application_name)
SELECT aname
FROM (SELECT 'andy_test' as aname) t
WHERE NOT EXISTS (select 1 from application_id_table ait WHERE ait.application_name = t.aname);
You should be able to plug your variable directly into the select statement, the same you would would with the VALUES statement.
Try this:
INSERT INTO application_id_table(application_name)
select 'andy_test'
WHERE NOT EXISTS (select 1 from application_id_table WHERE application_name = 'andy_test');

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

mysql insertion where not exists syntax error. I have no idea what is wrong

insert into creditcard_info (member_id,card_type,card_number)
values ('1','Discover','555')
where not exists (
select * from creditcard_info
where card_number='555' and
card_type='Discover')
I want to be able to check if a card number already exists..
If card_number exists and card card_type exists then don't add
else insert this new card number along with card type
I am having difficultly with inserting into a table where a certain number does not exists.
Im getting 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
creditcard_info where card_number='555')' at line 2
Thank you all in advance for helping me :)
It looks like you're trying to perform an INSERT ... SELECT statement.
However, adding a unique index in both fields should be more efficient.
You need to create a multi-column unique index. The code is as below:
ALTER TABLE creditcard_info ADD UNIQUE idx_card_number_card_type(card_number,card_type);
This should run as a separate query. And you need to add it once.
The other possible option is to add before insert trigger if the condition is more complicated than a simple unique check.
Here is the create trigger syntax:
Create Trigger card_type_unique_card_number_exists Before Insert on creditcard_info
FOR EACH ROW BEGIN
DECLARE it_exists INT;
Set it_exists=(select count(*) from creditcard_info where card_number='555' and card_type='Discover');
If it_exists>0 Then
#Throw a meaningful exception by let's say inserting into a table which doesn't exist or something
END IF;
END