Creating and populating a table with foreign keys using InnoDB - mysql

I have an InnoDB table that lists customer orders - this table records the customer's email address, contact information for the order, and the order id. This table uses innodb and contains roughly 220 million rows. What I do not have, is a table that lists the users.
Is it possible, perhaps using foreign keys, for me to create and populate a table that will contain a customer_id and e-mail address from the data that is in my orders table?
This is the query that I have so far:
INSERT INTO customers (email, last_order)
SELECT (email_address, order_date) FROM orders
ON DUPLICATE KEY
UPDATE last_order = MAX(order_date, last_order);
I believe this query will build the database, but it won't put the customer id into the row in the orders table, and I am not sure if it is the best approach to start with. Any suggestions?

You can achieve this it in 2 steps:
1st, fill in the customers table:
INSERT INTO customers (email, last_order ) SELECT email_address,
max(order_date) as last_order FROM orders GROUP by email_address;
2nd, update the orders table with customers' ids (assuming you have a field called customer_id in the orders table)
UPDATE orders o SET customer_id =
(SELECT id FROM customers WHERE email = o.email_address);
Finally, if you want to keep your customers table consistent, you can add an AFTER INSERT TRIGGER to the orders table to keep your customers table up-to-date.

Related

How would I delete all traces of a specific "Customer" from 2 tables? MySQL

I have 2 tables, Customer and Order.
I wish to delete the rows in which that particular Customer appears in. I have tried this,
DELETE FROM Customer
WHERE Email ='2ManySnakes#gmail.com' -- I was asked to associate the customer with an email.
UNION
DELETE FROM `Order`
WHERE O_CustomerID = 2;
Not sure if this will work. But I just want to know if the syntax is correct.
union used for joining 2 queries vertically, so it is no sense here in your query, you run 2 queries like this:
DELETE FROM Customer WHERE Email ='2ManySnakes#gmail.com';
DELETE FROM `Order` WHERE O_CustomerID = 2;
You just use two SQL statements. I presume these would be:
DELETE c FROM Customer c
WHERE CustomerId = 2;
DELETE o FROM `Order` o
WHERE O_CustomerID = 2;
There is no need to use the email for one table and the customer id for the other -- use the same identifier for both.
Note that you can also use cascading foreign key constraints. That would make it possible to delete the customer record from the customer table, and all related tables for that customer would also be deleted.
Is there a foreign key between the Customer and Order table?
If yes, you can delete from Order where (select from customer where customer_id = 2);
Commit;
Then delete from customer where customer_id = 2;
Commit;

Database relation and inserting a row

I am building a cash register for my work place. I am having a trouble with Mysql.
I have db with three tables.
orders (where it stores : list_id, order_id (FK from order_line table),Id (FK for product id from product table), qty, total).
order_line (Where it stores : order_id, order_date, order_time )
products (id,product_name,product_desc,price)
What i want to do is to add the order in database. Insert into order_line a date and time and order_id(auto increment)
Also insert the items into orders table where it can retrieve order_id from order_line table so i can have same order_num for each item in orders table.
so far, this is what i tried;
INSERT INTO order_line
VALUES('','04/25/2015','11.52.06');
INSERT INTO orders
VALUES ('','orders_ibfk_2','orders_ibfk_1','2',30.00);
and recieved an error: Cannot add or update a child row: a foreign key constraint fails (shoelacestore.orders, CONSTRAINT orders_ibfk_1 FOREIGN KEY (id) REFERENCES products (id))
Any help will be appreciated. Thank You
I think your id column data types are not integer. Make it integer if it is ok.
when you execute following query
INSERT INTO order_line
VALUES(0,'04/25/2015','11.52.06');
You will get a value for order_id. Just assume it is 344
And assume in your products table you have a product with id 98
Then you can use follwing query to insert into
INSERT INTO orders
VALUES (0,344,98,'2',30.00);
i assume all ids are integers
Guys i found the solution.
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
SET #last_id_in_T1 = LAST_INSERT_ID();
INSERT INTO T2 (col1,col2) VALUES (#last_id_in_T1,val2);
so basicly, T1 is the table for order_line which creates an auto increment order_id. SET #last_id_in_T1 = LAST_INSERT_ID(); copies the last order_id and inputs into orders table as i wished.
I hope this will help others as well.

Foreign Key reference in mySQL

In mySQL if I created two tables and on table contains a foreign key referenced to the other table. I have entered data in the other table and for the defined foreign key in that as well. Is there any way for the foreign key to automatically update in the second table without having to type in the entire data?
For example I have a customer table which has 2 fields- customerID and customerName. Another table is say a invoice table which has 3 fields- invoiceID, cost and customerID, where customerID is foreign key. So if I enter data in customer table and invoice table as the number of customers are very large I do not want to keep on entering the customerID in the invoice table. As customerID is a foreign key in the other table, how do I make it automatically reference it from customer table?
You can automatically add a predefined number, like 1, but that will assign all invoices to customer#1.
On the other hand, you can add customers automatically while adding invoices. For that, you need to control the customerID and if a customer with the given ID is not present, insert a new customer to the customer table with empty name. After that, you still need to enter names for those customers, but not by one and that would get things (maybe) easier.
I think you have a misleading idea here. I strongly suggest reading a book or seeing a tutorial online or examining an example project's database tables.
If you have the customer name in invoice data and customer data already populated, you could do
INSERT INTO tbl_invoice (invoiceData, invoiceData2, customerID)
SELECT 'value1', 'value2', customer.customerID
FROM tbl_customer customer
WHERE customer.customerName = 'customer name'
So you wouldn't need to deal with customer ids directly.
There is no automatic feature in MySQL to do exactly this. A trigger could be used for it if needed.

MySQL Query Update Multiple Tables

I have a contact management system and an sql dump of my contacts with five or six columns of data in it I want to import into three specific tables. Wondering what the best way to go about this is. I have already uploaded the sql dump...its a single table now in in my contact management database.
The tables in the crm require in the companies table only the contactID...and in the songs table:
companyID,
contactID,
date added (not required) and
notes (not required)
Then there is the third table, the contact table which only requires contactname.
I have already uploaded data to each of the three tables (not sure if my order is correct on this) but now need to update and match the data in the fourth table (originally the sql dump) with the other three and update everything with its unique identifier.
Table Structures:
+DUMP_CONTACTS
id <<< I dont need this ID, the IDs given to each row in the CRM are the important ones.
contact_name
company
year
event_name
event_description
====Destination Tables====
+++CONTACTS TABLE++
*contactID < primary key
*contact_name
+++COMPANIES TABLE+++
*companyID < primary key
*name
*contact_ID
*year
++++Events++++
*EventID < primary key
*companyID
*contactID
*eventname
*description
There are parts of your post that I still don't understand, so I'm going to give you SQL and then you can run them in a testing environment and we can take it from there and/or go back and start again:
-- Populate CONTACTS_TABLE with contact_name from uploaded dump
INSERT INTO CONTACTS_TABLE (contact_name)
SELECT contact_name FROM DUMP_CONTACTS
-- Populate COMPANIES with information from both CONTACTS_TABLE + dump
INSERT INTO COMPANIES (name, contact_ID, year)
SELECT d.company, c.contactID, d.year
FROM DUMP_CONTACTS AS d
INNER JOIN CONTACTS_TABLE AS c
ON d.contact_name = c.contact_name
-- Populate SONGS_TABLE with info from COMPANIES
INSERT INTO SONGS_TABLE (companyID, contactID)
SELECT cm.companyID, cm.contact_ID
FROM COMPANIES AS cm
-- Populate Events with info from COMPANIES + dump
INSERT INTO Events (companyID, contactID, eventname, description)
SELECT cm.companyID, cm.contact_ID, d.event_name, d.event_description
FROM DUMP_CONTACTS AS d
INNER JOIN COMPANIES AS cm
ON d.company = cm.name
I first populate CONTACTS_TABLE and then, since the contactID is required for records in COMPANIES, insert records from CONTACTS_TABLE joining the dump. SONGS_TABLE takes data directly from COMPANIES, and lastly the Events gets its data by joining COMPANIES and the dump.

How to delete multiple entries in mysql

I have db with multiple entries.
I Google out something like this
SELECT COUNT(*), item_id, text, number FROM ads
GROUP BY item_id, text, number
HAVING COUNT(*)>1;
this select (I think) all my multiple entries, I use SQLyog, ... and there is no option to press button and delete all results of this query.
but even if I select all one by one and delete, I would also delete original one, right?
I basically want to keep all unique entries and keep one of multiple items.
simple example
('1' 'Novi Sad' '123');
('1' 'Novi Sad' '123');
('3' 'Beograd' '124');
I want to keep
('1' 'Novi Sad' '123');
('3' 'Beograd' '124');
I know only basic mysql.
When you do delete entries make sure to reset your ID increment
ALTER TABLE 'table_name' AUTO_INCREMENT = 1
Can you just copy, drop and delete?
CREATE TABLE Copy_Temp as
SELECT item_id, text, number
FROM ads
GROUP BY item_id, text, number;
DROP Table ads;
RENAME TABLE Copy_Temp TO ads;
Select all unique records into a temp table.
Delete all records from original table.
Insert all records from your temp table into original table.
DELETE emp FROM employee emp, employee emp2
WHERE emp.id > emp2.id
AND emp.name = emp2.name
For example, you having the table employee in which there are duplicate records (having the same name multiple times) then this query will delete all the duplicate records.