MySQL syntax error : where not exists - mysql

I've been trying to insert a record in the database if it does not already exists and this is the query:
insert into evt(e_id, t_id)
values( '1597', '4')
where not exists( select id from evt where e_id = '4' and t_id = '1597');
that query returns with the following 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 id from evt where e_id = '4' and t_id = ' at line 1
I can't understand why it doesn't work

If you want to prevent duplicates in the database, then let the database do the work. Use a unique constraint or index:
create unique index unq_evt_eid_tid on evt(e_id, t_id);
This guarantees the data integrity, regardless of how values are inserted or updated. The database does the work for you.
Then you can prevent an error when inserting, by using on duplicate key update:
insert into evt(e_id, t_id)
values (1597, 4)
on duplicate key update e_id = values(e_id);
The on duplicate key prevents the code from generating an error.
I also removed the single quotes from the values. Ids are usually numbers. If they are really strings, add the quotes back in.

Try this :
INSERT INTO evt(e_id, t_id)
SELECT * FROM (SELECT '4', '1597') AS tmp
WHERE NOT EXISTS (
SELECT e_id FROM evt WHERE e_id = '4' and t_id = '1597'
) LIMIT 1;

Try this:
insert into evt(e_id, t_id) values( '1597', '4') where not in( select id from evt where e_id = '4' and t_id = '1597');

INSERT statement doesn't support WHERE clause.
You have multiple options. First do a select and if the condition is true INSERT OR Use ON DUPLICATE KEY
INSERT INTO evt
SET e_id = '1597', t_id = '4'
ON DUPLICATE KEY UPDATE
e_id = '1597', t_id = '4'
This needs your field to be an index ( Primary or unique )
Note: you shouldn't use quotes when inserting numbers as the mysql treat it like a string and tries to do a conversion and gradually it slows down your project. Also it is safer to insert numbers without quotes

I solved everything adding a unique pair like this:
ALTER IGNORE TABLE mytable ADD UNIQUE (field1,field2)

I think you are looking for UPDATE and not insert?
UPDATE `evt` SET `e_id`='1597', `t_id`='4'
WHERE `e_id` NOT in ('4') and `t_id` not in('1597');

MySQL INSERT Syntax does not support the WHERE condition
insert into evt(e_id, t_id) values( '1597', '4')
could be you need update
update evt
set e_id = '1597',
t_id = 4
where id not in ( select id from evt where e_id = '4' and t_id = '1597');
Or an insert select
insert into evt(e_id, t_id)
select '1597', '4'
from evt
where not exists( select id from evt where e_id = '4' and t_id = '1597');

Related

MySQL Trigger with IF statement

I'm trying to create my first MYSQL trigger, when an Inserted record with a role_id of 4 is inserted, I want it to insert another record using the same values but with a role_id of 5.
My best effort is:
CREATE TRIGGER auto_insert_member
AFTER INSERT ON staff_role
FOR EACH ROW
BEGIN
IF (NEW.role_id = 4) THEN
INSERT INTO staff_role
SET
start_date = NEW.start_date,
end_date = NEW.end_date,
person_id = NEW.person_id,
role_id = 5
END IF
END
I can't make it work and phpMyAdmin error messages are not helpful. What am I doing wrong?
It is possible that the syntax error is due to the mixing of the UPDATE and INSERT method:
UPDATE TABLE
SET COLUM1 = VALUE1,
COLUM2 = VALUE2;
INSERT INTO TABLE
(COLUM1, COLUM2)
VALUES (VALUE1, VALUE2);

MySQL UPSERT not recognizing alias

I have a query that performs an UPSERT (Insert - but if exists, update).
MySQL complains it isn't valid, here is the query:
insert into
mytable (user_id, num_products_observed, num_purchased_percent)
(select
A.user_id,
B.total 'num_products_observed',
case
when A.purchased is null then 0
else A.purchased/B.total
end 'num_purchased_percent'
from
(select user_id, count(prod_observed) 'total' from products where user_id = ? ) B
left join (select user_id, count(prod_purch) 'purchased' from products_purchased) A on B.user_id = A.user_id
) newsum -- <--- ISSUE IS HERE
ON DUPLICATE KEY UPDATE
num_products_observed = newsum.num_products_observed,
num_purchased_percent = newsum.num_purchased_percent
I hope this makes sense to you. The issue is at the line which reads ) newsum. MySql complains about the alias I'm giving the table. user_id is unique in this table (mytable).
It IS possible that B.total is null, in which case everything in newsum is null - which is fine, then I don't want to insert or update anything (or an update with user_id and zeros for all would be fine too).
Any thoughts on what I'm doing wrong? Thanks
Are you trying to use VALUES statements.
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement
dev.mysql

Mysql IF EXISTS THEN

So--i'm having an issue with my code. I'm testing it directly in the console and getting an "syntax 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 'IF EXISTS(SELECT * FROM user_inventory WHERE resource_id = '6'
AND uid ='1') T' at line 1
IF EXISTS(SELECT * FROM user_inventory WHERE resource_id = '6' AND uid ='1')
THEN UPDATE user_inventory SET resource_count = resource_count+1 WHERE resource_id = 6 AND uid = 1
ELSE INSERT INTO user_inventory(uid, resource_id, resource_count) VALUES (1, 6, 1);
I've never used the IF EXISTS clause before... So I'm not sure what i've done wrong.
The SQL IF statement can only be used within a stored program. You can't use it within a generic SQL context as you have attempted.
However, you do not need to use IF here:
Define a suitable uniqueness constraint on your user_inventory table:
ALTER TABLE user_inventory ADD UNIQUE (uid, resource_id)
Use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO user_inventory
(uid, resource_id, resource_count)
VALUES
(1, 6, 1)
ON DUPLICATE KEY UPDATE
resource_count = resource_count + 1

Mysql query to update row if exists?

I need an If, then, else query in mysql,
tried out the below,
if exists( select * from data_table where user_id =1 and link_id = 1) then update data_table set is_view = 1 where user_id = 1 else insert into data_table...
what is the correct way to do this?
if you only need to do this in mysql, then search insert on duplicate key. Or you can use a stored procedure. Check INSERT ... ON DUPLICATE KEY UPDATE Syntax
insert into data_table (user_id, link_id, other_column)
values (1, 1, 'value to insert or uodate')
on duplicate key update other_column='value to insert or update';

insert into table only if not exist on other table

I'm trying to do the following thing:
I have two tables: ReportImage (imageId, reportId, counter)
and userReportedImages (imageId, userId)
I want that every user will be able to report an image only once - this means that first I want to check if there is a row in 'userReportedImages' with the values (imageId, userId) if so do nothing, else create a row in 'ReportImage' with the values (imageId, reportId, counter), if such row already exist (other user reported that image) then I want to raise the counter.
so far before checking for same user report I had the following statement:
INSERT INTO ReportImage VALUES (imageId,reportId,1) ON DUPLICATE KEY UPDATE counter = counter+1
this statement is working fine.
I tried to change this statement to first check if the row exist on the other table, but I didn't manage to do it, can you help me?
First, you need to define a UNIQUE constraint or a compund column primary key on table ReportImage,
ALTER TABLE ReportImage ADD CONTRAINT tb_uq UNIQUE(ImageID, ReportID)
Give this a try,
INSERT INTO ReportImage(ImageID, ReportID, Counter)
SELECT 'imageID HERE' AS ImageID,
'userID HERE' AS ReportID,
1 AS Counter
FROM userReportedImages a
LEFT JOIN ReportImage b
ON a.imageId = b.imageId AND
a.userId = b.ReportID AND
a.imageID = 'imageID HERE' AND
a.userID = 'userID HERE'
WHERE b.imageId IS NULL OR
b.ReportID IS NULL
ON DUPLICATE KEY UPDATE counter = VALUES(counter) + 1
you could try using NOT EXISTS
insert into table2(`name`)
select * from (select 'name1' as name) tmp
where not exists(
select ('x') from table1 where name = 'test1'
);
SQL Fiddle
An insert trigger should be a solution for you: link