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.
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.
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'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, ... ]
I need to be able to add a set of values into a table every time a new user is added into my system.
When the user is added, I want to look into my 'Tags' table, and insert a new entry into the 'Tag_Score' table for each of the IDs in the 'Tags' table.
I tried the following based on something i found online but although the logic seems sound, it doesn't seem to be working
DECLARE #LoopVar INTEGER
SET #LoopVar = ( SELECT MIN(Tag_Score.T_ID)
FROM Tags ) WHILE #LoopVar IS NOT NULL
BEGIN
INSERT INTO `a3360218_DD`.`Tag_Score` (
`A_ID` ,
`T_ID` ,
`Score` ,
`Visits`
)
VALUES (
'" . $accountID . "', #LoopVar , '0', '0'
)
SET #LoopVar = ( SELECT MIN(Tag_Score.T_ID)
FROM TheTable
WHERE #LoopVar < T_ID )
END
The error given is:
#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 'WHILE #LoopVar IS NOT NULL
BEGIN
INSERT INTO `a3360218_DD`.`Tag_Score` (
' at line 2
Thanks in advance
Matt
You haven't posted any table layouts, so I'm shooting in the dark here, but this kind of query should work for you:
INSERT INTO Tag_Score (A_ID, T_ID, Score, Visits)
SELECT A_ID, T_ID, 0, 0
FROM Tags
WHERE A_ID = $accountID;
Note the removal of all those unnecessary back-ticks (ie `) that are only necessary when you have a schema name that is a reserved word, and look how readable it is now!
Keep things simple - avoid complex SQL if you can.
I think you might want CROSS JOIN, or maybe just a regular insert from...
insert into Tag_Score
select accountID, t.ID, 0, 0
from tags t
-- optional order by
-- order by t.ID