select if and update issue - mysql

Am using this sql to do an update on duplicate key
IF (SELECT COUNT(*) FROM `mlm_settings` WHERE `key` = 'notify_type' AND `user_id`=7 >0 )
UPDATE mlm_settings SET value='2' WHERE user_id = 7
ELSE
BEGIN
INSERT INTO `mlm_settings` (`key`, `value`,`user_id`) VALUES ('notify_type', '2',7)
END
by i get an sql error in mysql saying
#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 'IF (SELECT COUNT(*) FROM
`mlm_settings` WHERE `key` = 'notify_type' AND `user_id' at line 1
i can't figure what is the cause of the error, as the names of the tables are valid and the values are of the same data type
what could be the error?

You can only use IF statements in stored procedures, not normal queries.
If there's a unique index on (key, user_id) in the table, you can use:
INSERT INTO mlm_settings (`key`, value, user_id) VALUES ('notify_type', '2', 7)
ON DUPLICATE KEY UPDATE value = '2';

IF control block cannot be used OUTSIDE of functions. Try this:-
SELECT IF( EXISTS(
SELECT COUNT(*) FROM `mlm_settings` WHERE `key` = 'notify_type' AND `user_id`=7 >0), 1, 0)

Related

ERROR 1064: Cannot execute while loop in mysql using variables

I'd like to run the below query to insert into a table in a loop:
SET #maxid = ( select max( length( id ) ) from article ) ;
SET #x=1;
WHILE #x<= #maxid DO
INSERT INTO `article_responder`
(article_id, username, reply_id)
SELECT #x, p.username, p.id
FROM article AS a, post AS p
WHERE a.id=#x AND p.article_id=#x ;
SET #x = #x + 1;
END WHILE;
But I get this 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 'END WHILE' at line
Notice that article_id can not be auto incremented, because the bussiness loginc requires that after inserting the data, the next row in article_responder can be about any article. So I had no idea how to fill article_responder with usual joins.
How can I fix it?
I would suggest just making article_id a primary key auto increment column, and then doing the following INSERT INTO ... SELECT:
INSERT INTO article_responder (username, reply_id)
SELECT p.username, p.id
FROM post p
INNER JOIN article a
ON a.id = p.article_id;
Note that the logic WHERE a.id=#x AND p.article_id=#x is equivalent to saying that a.id = p.article_id.

MARIADB : Insert and Update table based on data from another table

/* Here is the code i used to merge but i get error and am unable update
Error : SQL Error [1064][42000] You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the righr syntax to use near 'Merge temp2 as t' at line 1
*/
BEGIN
MERGE temp2 as t
using temp1 as s ON (t.slno = s.slno)
-- Insert values when data no present
WHEN NOT MATCHED THEN INSERT VALUES
(s.slno,s.name,s.address);
-- Update when values present
WHEN MATCHED then UPDATE SET
t.slno = s.slno,
t.name = s.name,
t.address = s.address;
END
You could probably use this:
INSERT INTO temp2 (slno, name, address) SELECT slno, name, address FROM temp1
ON DUPLICATE KEY UPDATE
slno = VALUES(slno), name = VALUES(name), address = VALUES(address)

How do I use IF THEN ELSE to SELECT and INSERT or UPDATE Queries?

I've been trying to use the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(INSERT INTO users (id, username) VALUES (2, user2))
ELSE
(UPDATE users SET username = 'userUpdated')
But I keep getting
/* SQL Error (1064): 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 'INSERT INTO users (id) VALUES (2)) ELSE (UPDATE users SET id = 11)' at line 1 */
Also tried using the following query
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1)
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))
But this time I got
/* SQL Error (1064): 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 'ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'))' at line 4 */
Am I doing or understood something wrong?
The if statement can only be used in programming blocks, such as stored procedures, functions, and triggers.
In any case, MySQL offers simpler syntax for this functionality: insert . . . on duplicate key update.
To use it, id must have a unique index, unique constraint, or be defined as the primary key. Let me assume that a column so-named is already so-defined.
Then:
INSERT INTO users (id, username)
VALUES (2, user2)
ON DUPLICATE KEY UPDATE username = 'userUpdated';
Are you missing the END IF (and semi colons)?
IF EXISTS (SELECT id FROM users WHERE id = 1)
THEN
(SELECT username FROM users WHERE id = 1);
ELSE
(INSERT INTO users (id, username) VALUES (1, 'user'));
END IF;
Try This.
IF EXISTS (SELECT id FROM users WHERE id = 1)
begin
INSERT INTO users (id, username) VALUES (2, 'user2')
end
ELSE
UPDATE users SET username = 'userUpdated'
In MariaDB 10.1 and newer, you can use compound statements outside of stored procedures. This blog post gives a good description of what you can do with it.
Here's an example the blog:
BEGIN NOT ATOMIC
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
stmt1;
....
stmtN;
COMMIT;
END

Django migration sql for conditional triggers

I want to create a trigger that only inserts into table when the condition is met.
I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time.
Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person.
operations = [
migrations.RunSQL(
"DROP TRIGGER like_notification",
"""
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
IF (select user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id
BEGIN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
)
END;
"""
)
]
>>>django.db.utils.ProgrammingError: (1064, "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 'BEGIN\n INSERT INTO notification (type, type_id, article_id, is_re' at line 5")
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
BEGIN
DECLARE #user_same Boolean;
SELECT 1 into #user_same
FROM channel
WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id)
AND user_id = NEW.user_id;
IF #user_same <> 1
THEN
INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (
SELECT user_id from channel WHERE channel_id IN (
SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
END IF;
END;
>>>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 '#user_same Boolean;\n SELECT 1 into #user_same\n FRO' at line 4"
and
CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article
FOR EACH ROW
INSERT INTO notification (type, type_id, article_id, is_read, type_user_iduser_id)
VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id,
(
SELECT user_id from channel WHERE channel_id IN
(SELECT channel_id FROM article WHERE article_id = NEW.article_id)
)
WHERE NOT user_id = NEW.user_id;
>>>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 'WHERE NOT user
I don't really understand why none of them work. Any help would be much appreciated!
#variables are not DECLARED.
Either:
DECLARE user_same BOOLEAN;
SELECT 1 INTO user_same WHERE ...
or
SELECT #user_same := 1 WHERE ...
Better yet, this avoids the need for the variable.
IF (EXISTS SELECT * FROM ...)
Also, don't use the construct IN ( SELECT ... ); it is usually better to use WHERE EXISTS ( SELECT * FROM ... ) or JOIN ... ON ....
(There may be more problems after fixing those.)
Another easy way to do this.
You should add any symbols between ; delimiters for the appropriate converting MySQL syntax to the raw SQL.
CREATE TRIGGER trigger_name BEFORE INSERT ON table
FOR EACH ROW
BEGIN
IF NEW.number <> 'anynumber' AND NEW.number <> 'anynumber'
THEN
SET NEW.number = 'anynumber'; --
END IF; --
END
This example works due to the dash symbols.

Conditional update/insert in MySQL

I found here a topic about an MySQL IF, ELSE query,i adapted it but i can't figure it out what is the problem with it.
Here is the query:
IF (SELECT * FROM `jos_import03_07_2011` WHERE `cod_oem` = 'OP-4CL') IS NULL THEN
INSERT INTO `jos_import03_07_2011` (`tip_imp`, `tip_produs`, `producator`,
`cod_intern`, `desc`, `cod_oem`, `pret`, `valuta`) VALUES ('Imprimanta Laser',
'Piese Schimb', 'BROTHER', 'BR-200503', '', 'OP-4CL', '338.49', 'EUR');
ELSE UPDATE `jos_import03_07_2011` SET `pret` = '338.49' WHERE `cod_oem` = 'OP-4CL';
END IF;
And here is the 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 (SELECT * FROM
`jos_import03_07_2011` WHERE `cod_oem` = 'OP-4CL') IS NULL THE' at line 1
This is the original post:
Conditional mySQL statement. If true UPDATE, if false INSERT
Thanks,
Sebastian
UPDATE
Error code for IF EXISTS:
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
`jos_import03_07_2011` WHERE `cod_oem` = 'OP-4CL') THEN' at line 1
Any reason you can't use the INSERT ... ON DUPLICATE KEY syntax?
INSERT INTO `jos_import03_07_2011` (`tip_imp`, `tip_produs`, `producator`,
`cod_intern`, `desc`, `cod_oem`, `pret`, `valuta`)
VALUES ('Imprimanta Laser', Piese Schimb', 'BROTHER', 'BR-200503', '', 'OP-4CL', '338.49', 'EUR')
ON DUPLICATE KEY UPDATE SET pret = VALUES(pret)
would be far more efficient: one less query and far less code to debug.