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
Related
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.
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');
I've got a question about SQL (php), I want to INSERT data in my table. But I want to use the IF NOT EXIST value.
What I've tried:
INSERT INTO vrienden (id, userid, vriendmetid, accepted) VALUES (null, '1', '20', '0') WHERE NOT EXISTS (SELECT * FROM vrienden WHERE userid='1' AND vriendmetid='20')
I'm not sure what's wrong, because I get the following 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 vrienden WHERE userid='1' AND vriendmetid='20')' at line 1
Thanks.
You want insert . . . select, not insert . . . values:
INSERT INTO vrienden (id, userid, vriendmetid, accepted)
SELECT x.*
FROM (select null as id, '1' as userid, '20' as vriendmetid, '0' as accepted) x
WHERE NOT EXISTS (SELECT 1 FROM vrienden v WHERE v.userid = x.userid AND v.vriendmetid = x.vriendmetid);
However, you probably shouldn't be doing this in the INSERT. Instead, create a unique index/constraint:
create unique index unq_vrienden_userid_vriendmetid on vrienden(userid, vriendmetid);
This way, the database will ensure uniqueness of the columns, so your application does not have to.
This is my query :
SELECT vehicle,
CASE
WHEN vehicle IS NOT NULL
THEN (INSERT INTO tbl_vehicle_on_user (vehicle, userid) values
(SELECT `vehicle` FROM `tbl_missions` WHERE `id` = 4 ), (SELECT `id` FROM `tbl_users` WHERE `id` = 12))
FROM tbl_missions WHERE id = 4;
I need to insert a row to tbl_vehicle_on_user when vehicle is not null on id 4.
When i execute this query i receive this error from mysql workbench,
01:24:49 SELECT vehicle, CASE WHEN vehicle IS NOT NULL THEN (INSERT INTO tbl_vehicle_on_user (vehicle, userid) values (SELECT vehicle FROM tbl_missions WHERE id = 4 ), (SELECT id FROM tbl_users WHERE id = 12)) FROM tbl_missions WHERE id = 4 Error Code: 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 'INTO tbl_vehicle_on_user (vehicle, userid) values (SELECT vehicle FROM `tbl_mi' at line 4 0.000 sec
And i get a red line under 'INTO' when i hover over it, it says 'Syntax error, unexpected INTO, expecting ('.
I don't know what it means i tried to search the web but couldn't find anything if you know how to fix this i will appreciate it if you answer my question :)
THANKS!!
If you already know the userid should be 12, then just use 12 instead of SELECT id FROM tbl_users WHERE id = 12. Here is a valid insert-select statement.
INSERT INTO tbl_vehicle_on_user (vehicle, userid)
SELECT `vehicle`, 12 userid
FROM `tbl_missions`
WHERE `id` = 4 and vehicle is not null;
I'm trying to select a value (id) from a MySQL table and use it in a update statement - all in a MySQL query. The select is composed of 2 parts: if the id exists, it is returned; if not, 2 inserts are done and the id is returned.
I have the following query:
SELECT
(CASE a.id WHEN '' THEN (
DELIMITER //
INSERT INTO xxxx (item_id, date_created, date_modified) VALUES (3313, NOW(), NOW())//
INSERT INTO yyyy (item_id, locale_id, value, date_created, date_modified) VALUES(LAST_INSERT_ID(), 2, TRIM(SUBSTRING_INDEX('some text: 250 x 46 x 584', ':', 1)), NOW(), NOW())//
SELECT c.id FROM xxxx c JOIN yyyy d WHERE c.item_id=3313 AND d.value='some text' LIMIT 1
) ELSE a.id END
) AS trans_ref_id
FROM xxxx a JOIN yyyy b ON a.id = b.item_id
WHERE b.value='some text'
When i run it, i get the following error:
SQL 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 ')
ELSE a.id
END
)
as trans_ref_id
FROM xxxx' at line 2
Am I having the wrong approach here? Where is this error coming from?
You cannot do this with SQL. You need to use cursors. The manual has an example for you to look at. Probably best to put this in a stored procedure.
Your creative attempt does not conform to the SELECT+INSERT syntax, which is:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]