How to populate a mysql table with data from two other tables - mysql

I have two tables with a many-to-many relation, and a joint table between them, for example:
client (id, name)
address (id, address)
client_address (client_id, address_id)
I need to populate the client_address table with a line for every client, using a specific address, like:
client_id, address_id
1, 1
2, 1
3, 1
4, 1
etc...
I tried something like this (which obviously does not work):
INSERT INTO
client_address (`client_id`, `address_id`)
SELECT id from client,
SELECT id from address where address = 'My Address';
can I do this with a single query?

If you have to populate it manually just like your example you can try to use CROSS JOIN :
INSERT INTO
client_address (`client_id`, `address_id`)
SELECT c.id, a.id
FROM client c,
CROSS JOIN address a
WHERE address = 'My Address';
This will create a line for every client you have in CLIENT table and the address you chose in the WHERE clause

Related

Insert records from one table to multiple relational tables using MySQL

I have three tables customers, customer_entity, customer_info. I wanted to insert records from customers table to customer_entity and customer_info at same time, but customer_entity tables primary key will be part of customer_info table.
Assumed Code can we write something like this?
INSERT INTO customer_entity (mobile, name)
INSERT INTO customer_info (customer_entity_id,email, name)
SELECT mobile, name, email customers FROM customers
I dont want to use any programming language only MYSQL
This query may help you.
INSERT INTO customer_entity (mobile,email)
SELECT mobile, email FROM customer ORDER BY id ASC;
INSERT INTO customer_info (customer_entity_id, email)
SELECT customer_entity.id, email, (SELECT email FROM customer WHERE mobile= customer_entity.mobile) FROM customer;
Here the customer table is the main table which has data already and we are inserting it into customer_entity table and customer_info table with customer_entity_id.
You can try using SELECT LAST_INSERT_ID() also:
INSERT INTO customer_entity (mobile,email)
INSERT INTO customer_info (LAST_INSERT_ID(), email)
Docs
If you insert a record into a table that contains an AUTO_INCREMENT
column, you can obtain the value stored into that column by calling
the mysql_insert_id() function.

INSERT values from one table to another with the new id and coping new id to another table

I have sql query:
INSERT INTO users (name, username, email, params, password )
SELECT CONCAT (`IMIE_WL`,' ', `NAZ_WL`),
CONCAT (a.wid,'-',LPAD(a.cid, 4, '0') ,'-',LPAD(a.LP_H, 2, '0')),
b.AK_NAZWA,
CONCAT('{"language":"","helpsite":""}'),
CONCAT('SomePasswordSalted')
FROM source_data AS b
INNER JOIN loginy AS a ON a.ID_LOK = b.ID_LOK;
I need add to this another insert to this query like this:
INSERT INTO conector (id,ID_LOK) VALUES (LAST_INSERT_ID(),ID_LOK);
Any ideas for one query?

Remove duplicate in SSIS package with preference over a column data

I have duplicate rows in data coming from excel sheet. In the SSIS package, I am using Sort transformation where sorting is done in ascending order by the primary key column ID. But before removing the duplicates I want to see if the email column has email with my company's domain. If so, I want other rows removed than the one having this type of email addresses. What should I do? Please refer to the image attached below.
In the data above, I want to remove two rows of John where email address are john#gmail.com. In Maria's case, I want to remove two rows having email addresses maria#gmail.com, hence preserving rows having email addresses of the domain mycompany.com. If there are multiple rows for a user having email addresses of the domain mycompany.com, I want to keep any one row with the domain email address.
Suggest please.
you can do that in sql like Kobi showed, that may be easier. But if you prefer in ssis:
My test data:
Some points:
Conditional split: First you separate rows with mycompany and those without.
Sort and non_mycompany sort: sort both output on id and remove duplicates.
mycompany_multicast: create two copy of rows with mycompany
Merge join: left join rows without mycompany to rows with mycompany. Note the join order, the purpose is to get rows without mycompany and no matching id in rows with mycompany.
Conditional split1: take rows without mycompany and no matching id in rows with mycompany. you can check id from rows with mycompany, if the id is null then the row has no matching in rows with mycompany.
union all: union the final result
You can use a statement like this:
WITH T AS
(
SELECT ROW_NUMBER() OVER (partition BY id ORDER BY id, CASE WHEN email LIKE '%#mycompany.com' THEN 0 ELSE 1 END ) rn FROM persons
)
DELETE FROM T
WHERE rn > 1
It sort all rows by similar ID and email ( the prefered mail with #mycompany is the first of the list), then add a rownumber on each group, and to finish, it delete all rows wich have a rownumber superior to 1 ( theses are duplicates)
Here is the data to test:
CREATE TABLE Persons (
id NUMERIC(5),
NAME VARCHAR(200),
email VARCHAR(400) );
INSERT INTO persons
VALUES ( 100,
'john',
'john#mycompany.com'),
( 100,
'john',
'john#gmail.com'),
( 100,
'john',
'john#gmail.com');
INSERT INTO persons
VALUES ( 200,
'maria',
'maria#mycompany.com'),
( 200,
'maria',
'maria#gmail.com'),
( 200,
'maria',
'maria#gmail.com');
INSERT INTO persons
VALUES ( 300,
'jean',
'jean#mycompany.com'),
( 300,
'jean',
'jean#gmail.com'),
( 300,
'jean',
'jean#mycompany.com'),
( 300,
'jean',
'jean#mycompany.com');
INSERT INTO persons
VALUES ( 400,
'tom',
'tom#gmail.com'),
( 400,
'tom',
'tom#gmail.com');

Insert into table if a field value do not already exist

I want to insert values to a row in my customer table if the Name value I'm providing do not already exist,
After some searching I used this sql query to do it and it does not work :(
IF NOT EXISTS (SELECT Name FROM customer WHERE Name = 'Riyafa')
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
VALUES ('Riyafa', 'ABC', '555','1000');
Please instruct me why that is incorrect.
The if statement is only allowed in stored procedures, functions, and triggers. One way you can do this is:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT name, address, contactno, total_amount
FROM (SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount) t
WHERE NOT EXISTS (SELECT 1 FROM customer c WHERE c.name = t.name);
A better approach, however, is to have the database enforce uniqueness on the name. Start by creating a unique index or name:
CREATE UNIQUE INDEX idx_customer_name ON customer(name);
Then use a construct such as on duplicate key update:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount
ON DUPLICATE KEY UPDATE Name = VALUES(Name);
The expression ON DUPLICATE KEY UPDATE Name = VALUES(Name) actually doesn't do anything, but it prevents the INSERT from returning an error.

mysql create multiple tables from one table

I have one table which I have imported into mysql.
Now I need to create multiple related tables.
So basically I have currently got the following
start transaction;
Insert into Address (AddressLine1, AddressLine2, Town, County, Postcode)
Select Distinct Address_line_1, Address_Line_2, Town, County, Postcode from Import;
set addressLastId = last_insert_id();
INSERT INTO Organisation (Name, AddressID)
SELECT DISTINCT Supplier_Name, addressLastId FROM Import;
commit;
The second part where I use the last_insert_id never increments probably because it gets the last insert.
So I need to workout how i can get the previous id for each row inserted into the address table?
Would i need to have an inner loop within the address insert ?
Cheers
I agree with Tim.
After you've populated Address, then you could just run
INSERT INTO Organisation (Name, AddressID)
SELECT DISTINCT Import.Supplier_Name, Address.id
FROM Import INNER JOIN Address ON (set all the address lines and city etc =, since Im guessing there wasnt an address ID in the original import)
You could use a join for the second insert - join Address and Import, and insert the required fields from each into Organisation.
Getting the last insert ID will only work if you process each record sequentially.