How to use procedure variable in select and insert query in MySQL? - mysql

I have two variables
1. inserted_user_id,
2. inserted_address_id
in my MySQL procedure.
I need to use them in insert queries and select queries. Im trying something like
insert into user_new(name, company, email, customer_id) select name,
company, email, inserted_user_id from user_old;
insert into user_address_map(address_id, user_id) select
inserted_user_id,inserted_address_id ;
There two statements are not working. How to use procedure variable's value in the above sql statements?

First make a select to get all the info: (you need to declare these variables first)
SELECT name,
company,
email,
INTO varname, varcompany, varemail
FROM user_old
then use it into insert
INSERT INTO user_new
(name,
company,
email,
customer_id)
VALUES (varname,
varcompany,
varemail,
inserted_user_id);
edit:
First insert the Selected values and get the id of the inserted row
INSERT INTO user_new
(name,
company,
email)
SELECT name,
company,
email
FROM user_old
SET out_param = last_insert_id();
Then update this row with your param
UPDATE user_new
SET customer_id = inserted_user_id
WHERE id = out_param;

Related

How can i insert mutiple row from another database by using values

When I enter this command, there will be an error because there are two rows in tbl_carts where email is ABC#gmail.com. Is there a way to take mutiple row from one database to another.
My sql command is:
INSERT INTO tbl_history(orderid, email, product_id, qty) VALUES
('testing', (SELECT email FROM tbl_carts WHERE email 'ABC#gmail.com'),
(SELECT product_id FROM tbl_carts WHERE email='ABC#gmail.com'),
(SELECT qty FROM tbl_carts WHERE email='ABC#gmail.com'))
Error Message is:
Subquery returns more than 1 row
This is the correct way to do INSERT using SELECT values from other table:
INSERT INTO tbl_history(orderid, email, product_id, qty)
SELECT 'testing', email, product_id, qty FROM tbl_carts WHERE email='ABC#gmail.com';
Here's a reference from the official documentation

Mysql insert from multi source

I need to insert into table with 3 columns, 2 columns from a select and one column external.
Like this:
Insert into customer(username, fullname, rate)
values
((select username, fullname from users), 1500)
It return : column count doesnt match
You want the insert ... select syntax, with a literal value in the third column:
Insert into customer(username, fullname, rate)
select username, fullname, 1500 from users

MySQL : add data from another database, starting on specific row, user_id is primary, need to insert incrementing numbers starting from 20

I have an user table with 19 rows (first row is admin). I need to add more, so I have another database with a table having more than 1.400.000 users.
My table has an "user_id" as primary key, INT(11), no auto-increment. I need to add users starting in row 20, and only "first_name", "last_name" and "email".
My first try:
INSERT INTO mydatabase.users (first_name, last_name, email) SELECT first_name, last_name, email FROM anotherdatabase.users
That gets me a "Field 'user_id' doesn't have a default value".
I understand it is because user_id is primary key and cannot be null. So, again, it is int(11), non auto-increment.
So I want to add 20,21,22,23 and so on, along the other data. I searched a lot for about 5 hours and can´t seem to find anything I can understand.
Thank you in advance.
To get your numbers starting from 20:
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT 19+row_number() over (),
first_name,
last_name,
email
FROM anotherdatabase.users
19+row_number() over ()
'row_number()' = Number of current row within its partition (Mysql documentation)
'over ()' - defines a partition without condition; so in fact counts for the entire table
Details for both can be found under MySQL Window Function concepts and syntax
19+ - ...
Alternatively - if the MySQL version < 8.0:
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT (select 20+count(*)
from anotherdatabase.users u1 where u1.id < u.id) as id,
first_name,
last_name,
email
FROM anotherdatabase.users u
This does rather assume that you have a user_id on the other table as well.
The inner select just counts how many records are in the original database that have a smaller id than the record that is being returned at that point (and adds 20 to have the numbering start at 20).
And a third option (not depending on the existence of user_id):
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT ( #row_num:=#row_num+1 AS user_id,
first_name,
last_name,
email
FROM anotherdatabase.users u,
(SELECT #row_num:=19) var;
I'm not a great fan of this as it involves creation of variables to keep track of the row number.
Write a procedure that use variable. for i < 1400020 , you would need to count the number of rows in anotherdatabase.users then add the figure with 20.
DELIMITER $$
CREATE PROCEDURE insert_test_data()
BEGIN
DECLARE i INT DEFAULT 20;
WHILE i < 1400020 DO
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT i,first_name, last_name, email FROM anotherdatabase.users;
SET i = i + 1;
END WHILE;
END$$
DELIMITER ;
CALL insert_test_data();
DROP PROCEDURE insert_test_data;
I found a simpler way, using variables. I still can´t believe it. It worked like a charm
SET #i=19;
INSERT INTO mydatabase.users(user_id, first_name, last_name, email)
SELECT #i:=#i+1,
first_name,
last_name,
email
FROM anotherdatabase.users;

Insert multiple rows with fields from select [duplicate]

I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
Of course you can.
One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).
We all know this works.
INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT `col-1`,`col-2`
===========================
Below method can be used in case of multiple "select" statements. Just for information.
INSERT INTO `TableName`(`col-1`,`col-2`)
select 1,2 union all
select 1,2 union all
select 1,2 ;
The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid

Select and Insert MySQL with distinct record

INSERT INTO numbers (type, number)
VALUES 'telephone', SELECT DISTINCT tel FROM flat_data
I am attempting to select distinct numbers from one table and then insert them into another table.
However I need to manually set the type column that I am inserting into manually.
I can do it without the DISTINCT but I can't get my head around how to do it with!
INSERT INTO numbers (type, number)
SELECT DISTINCT 'telephone', tel
FROM flat_data