mysql conditional insert - if not exists insert - multi value insert - mysql

From my previous question this was the solution I am accepting:
INSERT IGNORE INTO table_name
SET name = 'phill',
value = 'person',
id = 12345;
But I also wanted to know if I could be multiple values like this
INSERT IGNORE INTO table_name
SET (name = 'phill', value = 'person', id = 12345),
(name = 'bob', value = 'person', id = 12346);

INSERT IGNORE INTO table_name(name,value,id) VALUES
('phill','person',12345),('bob','person',12346)

Related

During Update Perform For Each On Last Insert ID

I have a very simple procedure which performs an update on multiple rows. Is their a way I can loop through the insert id of each updated row?
BEGIN
UPDATE testTable set testValue = 2
where username = inputUser and flag = 1;
//for each update performed, insert LAST_INSERT_ID() into tableB
END
is this possible? If so, can you lead me in the right direction?
LAST_INSERT_ID only gives you one last id. You can do multiple inserts without a loop. You can use the output of SELECT query and insert to the desired table. You can do something like that:
BEGIN
UPDATE testTable set testValue = 2
where username = inputUser and flag = 1;
INSERT into tableB (column1, column2)
SELECT column1, column2 FROM testTable
WHERE username = inputUser and flag = 1;
END
For example:
User (username, password)
UserLoginLog (username, last_log_in_date)
INSERT INTO UserLogInLog (username, last_log_in_date)
SELECT username, NOW()
FROM User
WHERE username = "JohnDoe"

Parameterized nested query

I'm trying to parameterize the following insert with a nested select.
INSERT IGNORE INTO table1 (creation_timestamp, str1, str2)
(SELECT now(), "param1", str2 FROM table2 WHERE key = "param2");
I'd like something like
INSERT IGNORE INTO table1 (creation_timestamp, str1, str2)
(SELECT now(), ?, str2 FROM table2 WHERE key = ?)
VALUES ("param1", "param2");
Anyone know how I can accomplish something like this?
Not exactly the same, but very similar.
You can use prepared statements:
http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
Example:
PREPARE soExample
FROM 'INSERT
INTO usr (id, username, profile_pic)
VALUES (NULL, ?, (SELECT name
FROM customers
WHERE id = ?
LIMIT 1))';
SET #uname = "someUserNameForTheExample";
SET #id = "1";
EXECUTE soExample USING #uname, #id;
Or you can user procedure or/and functions as well
FUNCTION
DROP FUNCTION IF EXISTS insertExample$$
CREATE FUNCTION insertExample(userNameVar VARCHAR(255), uID INT(11)) RETURNS BOOLEAN
BEGIN
INSERT
INTO usr (id, username, profile_pic)
VALUES (NULL, userNameVar, (SELECT name
FROM customers
WHERE id = uID
LIMIT 1));
IF ROW_COUNT() > 0 THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END$$
FUNCTION USE
SELECT insertExample("SomeUsername" 2);
Perhaps you should start by reading https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html. As Mysql Functions enables parameterized input for pre-build queries.

IF Exists Then Update MySQL

I am trying to update a row if its exists, if it does not exist then I want to perform an insert into the table. The picture.id & picture.picturepath are a unique key. I have looked at some examples but I am not sure What I am doing wrong.
I have come across on duplicate key update, not sure if this is relevant to what I am trying to achieve.
Error message: 1064- You have an error in your SQL syntax near 'UPDATE picture SET picture.picturecontent = ipicturecontent WHERE picture.id at line 5"
IF EXISTS( SELECT * FROM picture WHERE picture.id = ipictureid
AND picture.picturepath = ipicturepath) THEN
UPDATE picture
SET picture.picturecontent = ipicturecontent
WHERE picture.id = ipictureid
AND picture.picturepath = ipicturepath
ELSE
INSERT INTO picture (picture.id, picture.picturecontent,picture.picturepath) VALUES (ipictureid, ipicturecontent, ipicturepath)
https://stackoverflow.com/a/10095812/1287480 <- Credit where credit is due
INSERT INTO models (col1, col2, col3)
VALUES ('foo', 'bar', 'alpha')
ON DUPLICATE KEY UPDATE col3='alpha';
don't forget THEN, BEGIN and END
IF EXISTS( SELECT * FROM picture WHERE id = ipictureid
AND picturepath = ipicturepath)
THEN
BEGIN
UPDATE picture
SET picturecontent = ipicturecontent
WHERE id = ipictureid
AND picturepath = ipicturepath
END;
ELSE
BEGIN
INSERT INTO picture (id,
picturecontent,
picturepath)
VALUES (ipictureid, ipicturecontent, ipicturepath)
END;
END IF;

MySQL: How to insert multiple rows into one table for each id of another query?

I have a key-value table and I need to insert multiple rows for each selected id from another table.
I get the user id:
SELECT #id := id FROM user WHERE email = 'my#email.com';
I get the ids of things by user id:
SELECT #things := id FROM `things` WHERE `owner_id` = #id;
Now I need to insert multiple values into key-value table for each #things. And problem here is that I cannot use a select subquery, because I need to insert inline values, like:
INSERT INTO key_value (key, value)
VALUES (
#things, 'CUSTOM VALUE 1'
),
VALUES (
#things, 'CUSTOM VALUE 2'
);
BUT, it does not work. The last query is obviously wrong. Any help would be much appreciated.
EDIT:
Looks like I need multiple queries to do that:
SELECT #id := id FROM user WHERE email = 'startour#netron.no';
INSERT INTO key_value (`key`, `value`)
(
SELECT id, 'CUSTOM_VALUE_1'
FROM `things`
WHERE `owner_id` = #id
);
INSERT INTO key_value (`key`, `value`)
(
SELECT id, 'CUSTOM_VALUE_2'
FROM `things`
WHERE `owner_id` = #id
);
INSERT INTO key_value (key, value)
SELECT user.id as key, things.id as value FROM user
left outer join things on user.id=things.owner_id
WHERE user.email = 'my#email.com'

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;