MySQL IF THEN ELSE - mysql

I'm trying to make a IF EXISTS UPDATE ELSE INSERT statement but I get errors around the UPDATE line. I could do this in two separate queries but I'm not sure what would be better.
I've tried to follow this guide but didn't manage to make my query work. https://blog.udemy.com/sql-if-then/
IF EXISTS
(
SELECT 1
FROM `table`
WHERE
`column` = 'value'
)
THEN
(
UPDATE `table` SET
`date` = NOW()
WHERE
`column` = 'value'
)
ELSE
(
INSERT INTO `table` SET
`date` = NOW(),
`column` = 'value'
)
END IF
END

Would this help?
INSERT ... ON DUPLICATE KEY UPDATE
https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
In your case "column" would be a unique key

Related

MySQL issue : adding the result of a query to a column in the same table

SELECT CONCAT(
from_unixtime(lastSaleTime/1000, '%Y-%d-%m %h:%i:%s.'),
CAST(EXTRACT(MICROSECOND FROM from_unixtime(lastSaleTime/1000))/1000
AS SIGNED)
) FROM IEX_Tick;
This code returns a column of values, and I want to add all that data to a new column that I created. This was suggested last time:
UPDATE IEX_Tick SET SomeColumn = (
SELECT CONCAT(
from_unixtime(lastSaleTime/1000, '%Y-%d-%m %h:%i:%s.'),
CAST(EXTRACT(MICROSECOND FROM from_unixtime(lastSaleTime/1000))/1000 AS SIGNED)
) FROM IEX_Tick;
)
However I get the error "You can't specify target table 'IEX_Tick' for update in FROM clause. I looked that up and we have tried some of the workarounds, for example:
UPDATE IEX_Tick SET SomeColumn = (
SELECT CONCAT(
from_unixtime(lastSaleTime/1000, '%Y-%d-%m %h:%i:%s.'),
CAST(EXTRACT(MICROSECOND FROM from_unixtime(lastSaleTime/1000))/1000 AS SIGNED)
) FROM (Select * from IEX_Tick) as RRR;
)
But it still doesn't work
Simply eschew the subquery:
UPDATE IEX_Tick
SET SomeColumn = CONCAT(from_unixtime(lastSaleTime/1000, '%Y-%d-%m %h:%i:%s.'),
CAST(EXTRACT(MICROSECOND FROM from_unixtime(lastSaleTime/1000))/1000 AS SIGNED)
);

Can you suggest mysql function like this?

I'm sorry if this question is stupid. What I want to do:-
<---'type' is a parameter of my procedure--->
SELECT * FROM `table1` WHERE
CASE type
WHEN 'some' THEN `column1`='column1string'
WHEN 'somestr' THEN `column2` = 'column2string' AND `column1` = 'column1string'
WHEN 'somestring' THEN `column3` = 'column3string'
END IF;
But I want to write more sql queries when using case statement:-
CASE type
WHEN 'some' THEN SELECT * FROM `table1` WHERE `coumn1`='column1string';
WHEN 'somestr' THEN SELECT * FROM `table1` WHERE `coumn2`='column2string' AND `column1` = 'column1string';
WHEN 'somestring' THEN SELECT * FROM `table1` WHERE `coumn2`='column2string';
END CASE;
How can I do this without writing the same query more times. because I have 40 strings like this for comparing.
I think you can just use boolean logic:
SELECT t.*
FROM `table1` t
WHERE (type = 'some' AND `column1` = 'column1string') OR
(type = 'somestr' AND `coumn2` = 'column2string') OR
(type = 'somestring' AND `coumn2` = 'column2string');

MySQL update or insert for tables without primary key

I know the simple way to perform update or insert is using 'REPLACE' but it needs a primary key, how about in the case of a table without primary key?
I have 5 columns in my table:
remark_id(the auto-increment primary key)
user_id
remark_user_id
remark
last_modified
I wish to check whether the pair of user_id and remark_user_id exists first before updating the remark, else a new row will be created to save the remark with the user_id and remark_user_id.
Here's my code
INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
SELECT 1,3 ,'testing123'
FROM dual
WHERE NOT EXISTS
(SELECT *
FROM `users_remark`
WHERE `user_id` = 1
AND `remark_user_id` = 3)
After running the SQL, nothing happens in my Database. No record was added or updated.
[Edited]
Code changes using IF...ELSE... but it comes with some syntax errors on first line
#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 EXISTS (SELECT * FROM users_remark WHERE user_id' at line 1
IF EXISTS (
SELECT * FROM `users_remark`
WHERE `user_id`=1 AND `remark_user_id` = 3
)
THEN UPDATE `users_remark` SET `remark` = 'testing123'
WHERE `user_id`=1 AND `remark_user_id` = 3
ELSE
INSERT INTO `users_remark` SET `remark` = 'testing123', `user_id`=1, `remark_user_id` = 3
Here is the query with both INSERT and UPDATE clauses (T-SQL syntax):
IF [condition here] BEGIN
UPDATE `users_remark`
SET `remark` = 'testing123'
WHERE `user_id`=1
AND `remark_user_id` = 3
END
ELSE BEGIN
INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
VALUES (1, 3, 'testing123)
END
EDIT: Same query with MySQL syntax
DECLARE #numrecords INT
SELECT #numrecords = count(*)
FROM `users_remark`
WHERE `user_id` = 1
AND `remark_user_id` = 3
IF #numrecords > 0 THEN
UPDATE `users_remark`
SET `remark` = 'testing123'
WHERE `user_id`=1
AND `remark_user_id` = 3
ELSE
INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
VALUES (1, 3, 'testing123)
END IF
Hope this will help you.
I finally try on putting code to php, it works and much easier to understand.
$checkRemark = mysqli_query($GLOBALS['db_conn'], "SELECT * FROM `users_remark` WHERE `user_id`=".$data['uid']." AND `remark_user_id` = ".$data['ruid']);
if (mysqli_num_rows($checkRemark)>0){
$remarkSql = "UPDATE `users_remark`
SET `remark` = '".$data['remark']."'
WHERE `user_id`=".$data['uid']."
AND `remark_user_id` = ".$data['ruid'];
} else {
$remarkSql = "INSERT INTO `users_remark` (`user_id`, `remark_user_id`, `remark`)
VALUES (".$data['uid'].", ".$data['ruid'].", '".$data['remark']."')";
}

MySQL - "insert if not exists" query?

I'm trying to write a MySQL query which will update a blog post view counter if the user has not visited the post in the last 24 hours. I'm trying to write something like this (but this does not work):
IF EXISTS (
SELECT 1
FROM `posts-views`
WHERE
`ip` = '".$_SERVER['REMOTE_ADDR']."'
AND
`time` > ".($time-60*60*24)."
AND
`post` = $id
) THEN
NULL
ELSE
INSERT INTO `posts-views`
(`post`, `time`, `ip`, `user`)
VALUES
($id, $time, '".$_SERVER['REMOTE_ADDR']."', $me)
What's the correct way to fix the query?
From what I see you cannot use INSERT IGNORE in that case, but something like following should do the job :
INSERT INTO `posts-views`
(`post`, `time`, `ip`, `user`)
SELECT $id, $time, '".$_SERVER['REMOTE_ADDR']."', $me
FROM dual
WHERE NOT EXISTS (
SELECT 1
FROM `posts-views`
WHERE
`ip` = '".$_SERVER['REMOTE_ADDR']."'
AND
`time` > ".$time-60*60*24."
AND
`post` = $id
)
I completely omit escaping variables which definitely should be done in real code.
UPDATED - added from dual to avoid syntax error

mysql REPLACE INTO and optional values IFNULL

I'm trying to do something like this inside of a stored procedure:
REPLACE INTO mytable
SET myid = `IDvalue`, mytitle = `sMyTitle`, myoptionalvalue = IFNULL(`sMyOptValue`, myoptionalvalue);
But not seems to work, any idea how to do this?
Thanks!
The REPLACE INTO syntax works exactly like INSERT INTO except that any old rows with the same primary or unique key is automaticly deleted before the new row is inserted.
This means that instead of a WHERE clause, you should add the primary key to the values beeing replaced to limit your update.
REPLACE INTO myTable (
myPrimaryKey,
myColumn1,
myColumn2
) VALUES (
100,
'value1',
'value2'
);
...will provide the same result as...
UPDATE myTable
SET myColumn1 = 'value1', myColumn2 = 'value2'
WHERE myPrimaryKey = 100;