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, ... ]
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 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;
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
I just moved an app from a local instance where I used Postgres to a Google Compute Engine virtual instance where I'm using Google Cloud SQL, built on MySQL.
Ever since the move, this SQL query is no longer working:
"UPDATE events e SET e.photographers = up.photographers FROM (VALUES "+ value_pairs +") AS up(id, photographers) WHERE up.id = e.id"
where value_pairs = (1,2)
Here's the exact error I'm seeing:
error running query { [Error: ER_PARSE_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 'FROM (VALUES (1,2)) AS up(id, photographers) WHERE up.id = e.id' at line 1]
The output seems correct ... anyone see what I'm doing wrong?
Update / Solution
Should have clarified, value_pairs can grow to be multiple values, i.e. ((4,2), (6,1), (10,3), ...)
Due to the relatively simple nature of this query, I ended up going with an INSERT query using ON DUPLICATE KEY clause:
("INSERT INTO events (id,photographers) VALUES "+ value_pairs + "ON DUPLICATE KEY UPDATE photographers=VALUES(photographers)"
You should be able to replace (VALUES "+ value_pairs +") AS up(id, photographers) with something like this:
mysql> (SELECT 1 AS photographers, 2 AS id) UNION (SELECT 3, 4) UNION (SELECT 5, 6);
+---------------+----+
| photographers | id |
+---------------+----+
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
+---------------+----+
3 rows in set (0.00 sec)
mysql>
You could create a temporary table to run your query in MySQL:
create temporary table src ...
insert into src values ...
And then run your update using src. It's not as pretty as the anonymous temporary table that you're currently using, but it'll work.
Another approach is to use a giant case statement:
update events
set photographers = case id
when 1 then 2
...
end
where id in (1, ...)
Use simple update:
UPDATE events
SET photographers = 2
WHERE id = 1;
MySql doesn't support the non-standard syntax of PostgreSql.
If multiple values are needed, a multitable update syntax might be used:
http://dev.mysql.com/doc/refman/5.7/en/update.html
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
One option is to insert values to a temporary table - as #Denis wrote - then perform an update:
UPDATE table t, temporary_table tmp
SET t.photographers = tmp.photographers
WHERE t.id = tmp.id
Another option is - as #Razvan Musaloiu-E. wrote - build a dynamic query with union:
UPDATE table t, (
SELECT 1 AS id, 2 AS photographers
UNION
SELECT 5, 7
UNION
SELECT 15, 67
UNION
.....
.....
.....
.....
UNION
SELECT 234, 567
) AS tmp
SET t.photographers = tmp.photographers
WHERE t.id = tmp.id