Copy data from few tables using SQL script - mysql

So let's say I have a table Car and it has primary key ID, columns BrandID (ref to table Brand), Price, Comment and others.
.
The thing I need to do is to copy columns Price and Comment to the new table.
But also for every Car element I need to go to Brand table and get specific Brand Name depending on BrandID value and also copy it to the new table
How can I accomplish this via SQL script?

Create the new table direct from the SELECT statement with JOINed tbales
CREATE TABLE NEW_TABLE SELECT Price, Comment, name FROM car c INNER JOIN brand ON b.ID = c.BrandID

You can use
CREATE TABLE ... SELECT statement...
Take a look at this mysql document for details
https://dev.mysql.com/doc/refman/8.0/en/create-table-select.html

Related

Create Table (new columns) and columns from different table

So For example. I have 1 table
and the name of the table is Suppliers
Contains :
1. SupplierName
2. SupplierID
I want to create another new table name Contracts
which contain new columns for
1. ContractID (new column)
2. SupplierID(from "Suppliers" table)
3. ContractValue (new column)
How do i do it?
I have researched and most of them told me to use Create table and then select, But it wont work and also ive tried alter table but still not working.
CREATE TABLE Contracts (
ContractID INT NOT NULL,
SELECT SupplierID
FROM Suppliers,
ContractValue INT NOT NULL,
ContractStart DATE NOT NULL)
These codes are not working so I'm not sure what is the solution.
CREATE TABLE Contracts (
ContractID INT NOT NULL,
(SELECT SupplierID
FROM Suppliers),
ContractValue INT NOT NULL,
ContractStart DATE NOT NULL)
I expect the result to be new table with ContractID (new column), SupplierID (from table Suppliers) and another new column named ContractValue
Think of Select query result set as a table or data grid.
So "SELECT [some fields] FROM [some table]" returns data grid where each row contains some fields from the table.
Therefore you can define table as select query with data OR alternatively specify the structure and create empty table. Most likely you don't want to mix those two approaches.
In your case, SupplierID field of contract table is a reference to SupplierID of Supplier table. In SQL it's called "foreign key". Theoretically you can use select statement in order to create new table and when you play a lot with database queries, you'll choose most convenient and faster way depending on your needs.
But when you start learning, it's better to create an empty table with structure and then insert data using new fields and existing data for the foreign key.
Therefore, the query will be something like:
CREATE TABLE Contracts (
ContractID INT NOT NULL,
SupplierID INT NOT NULL,
ContractValue INT,
ContractStart DATE
);
And then you can insert data using existing values from supplier table:
INSERT INTO Contracts (SupplierID)
SELECT SupplierID FROM Suppliers
Of course this is very simplified description
First, you have to specify ContractID as primary key. Then the query above will work only if you specify primary key as auto increment value, otherwise you have to use some logic and specify it explicitly.
In addition you have to specify default values if you want to use NOT NULL fields.
You can also specify SupplierID as foreign key, so only existing values will be added and some other integrity relationships will be supported.
See any MySQL or SQL documentation for details.
I don't know whether the below way could solve your problem
Make a copy of Suppliers table
Delete unnecessary column from the copied table
Add new column that you want to it.
You can use CTAS command.
CREATE TABLE Contracts as
SELECT
0 as ContractID,
SupplierID,
0 as ContractValue,
now() as ContractStart
FROM Suppliers;
This will create a table with all fields. The default value is to specify the dataType. You can update the table with relevant value or have a join in the select clause itself.
The basic syntax for creating a table from another table is as follows
CREATE TABLE NEW_TABLE_NAME AS
SELECT [ column1, column2...columnN ]
FROM EXISTING_TABLE_NAME
[ WHERE ]
Here, column1, column2... are the fields of the existing table and the same would be used to create fields of the new table.
Example
Following is an example, which would create a table SALARY using the CUSTOMERS table and having the fields customer ID and customer SALARY −
SQL> CREATE TABLE SALARY AS
SELECT ID, SALARY
FROM CUSTOMERS;
last week I did, as you want to do.
Only two steps I was followed:
Export existing table.
Open in notepad++ and change the existing table name, add my new columns and Import.
Thanks

Generate ID Keys for MySQL Values

I currently have a MySQL table that is formatted as such -
What I would like to do is move this data to a new table, but instead of having VARCHAR's for the part, location, and customer data, I would like to assign each of them autoincrementing id's based on the value. For example, part "DEF" would have an id of 1 and part "GHI" would have an id of 2. This is what the table would look like -
Is there an SQL query to do this?
You want the values in the part and loc columns to be auto-incrementing integers, or you have type tables for part and loc respectively with auto-incrementing integers?
Option-1:
Create the new table with a different name than the old one. Insert the entries into the new table from the old table mapping values to integers as you go.
INSERT INTO new_table_name (part, loc, quan, date, customer)
SELECT CASE
WHEN part = 'DEF' THEN 1
WHEN part = 'GHI' THEN 2
END
, CASE
WHEN loc = '...' THEN 1
WHEN loc = '...' THEN 2
WHEN loc = '...' THEN 3
END
, quan
, date
, customer
FROM original_table
Option-2:
The following is a sample type table for part:
If you have a type table for part and loc, you can do something like this...
SELECT part.id
, loc.id
, quan
, date
, customer
FROM original_table orig INNER JOIN part prt
ON orig.part = prt.value
INNER JOIN loc
ON orig.loc = loc.value
As far as I know, there is no way to use the auto-increment feature to directly generate values for the table you described.
It is good practice to create new tables and populate it rather than trying to change the existing one (Especially, if your application is live and you are dealing with customer data).
I would suggest you to create a new schema as follows:
Schema Diagram
You can populate all the new tables using your existing table and assign all the primary keys to Auto-increment.
This helps you to scale your application and maintain it easily.

MYSQL Move data from one table column to another table column if condition is matched

i'm not really an mysql guy more like a php guy :)
I have an issue with copying values from one table column to another table column.
The trick is that the data should be copied only if condition is matched. So basically i want to transfer categoryID from one table to another if postIDs are the same.
i have two tables news and news_in_category
in news table i have the following columns (id, title, categoryID)
in news_in_category i have the following columns (newsId, newsCategoryId)
So i want to move newsCategoryId to categoryID if newsId is the same as id.
For example if news table id=99 it should look up in news_in_category table find the newsId with value 99 and copy the newsCategoryId value to news table categoryID with id 99
Hope it makes sense to you :)
Thank you!
Try:
UPDATE news n
JOIN news_in_category nic ON n.id = nic.newsId
SET n.categoryID = nic.newsCategoryId
It looks like you might have a redundant functional dependency: newsId -> categoryId. If so, you could drop the news_in_category table without any loss of information, after running the query above.

Updating a field with one from another database where a field matches in both

I'm trying to update all the prices in one database with the prices from another where the product code matches (which isn't the primary key), whilst leaving the other fields columns untouched.
INSERT INTO inventory
SELECT * FROM temporary_table
ON DUPLICATE KEY UPDATE price = VALUES(price)
This is just duplicating the whole product where the code matches
Thanks in advance
Try using replace instead of insert. select all the columns from inventory table except the one you want to update(price)
REPLACE INTO inventory
SELECT b.col1, b.col2......... a.price
FROM temporary_table a, inventory b
where a.product_code = b.product_code

sql to populate newly created link table

I would be really grateful if somebody could help me out with this..
I actually have 2 tables in my database: books and authorlist.
The book table contains a field 'book_aut' which contains the foreign key of the authorlist table.
The authorlist table has only 2 fields, the primary key and the 'authors' column which contains a list of names.
I have to modify the table structure so that books table is linked to an authors table via a link table called 'lnk_book_author'
So my first task is to create a new table called 'authors' which contains 3 fields - primary id, name, surname, which i already did.
Next, i created the link table called 'lnk_book_author' and this one contains 3 fields, the primary id, book_fk, author_fk. The book_fk and author_fk refer to the id of the book and author respectively.
My problem is that i have more than 6000 entries in the books table and i would like to know how to populate the link table with the book id and the author id.
Is there a way of doing that using sql instead of manually populating the lnk_book_author table.
Hope i was clear enough..
Thanks a lot for any suggestion provided.
I'm infering the IDs already in your new [authors] table mean nothing with regards to the old tables. If that's the case you need to relate the records by the Name. And there I need to assume that the names are entered Identically. If they're not, it may not be possible to do. We'd need to know a lot more specifics to be sure...
INSERT INTO
lnk_book_author
SELECT
Books.PrimaryKeyFieldName,
Authors.PrimaryKeyFieldName
FROM
Books
INNER JOIN
AuthorList
ON Books.BookAut = AuthorList.PrimaryKeyFieldName
INNER JOIN
Authors
ON CONCAT(',', AuthorList.Authors, ',') LIKE CONCAT('%,', Authors.Name, ',%')
Something like that ?
INSERT INTO lnk_book_author(book_fk,author_fk)
SELECT b.book_id,a.author_id
FROM books b INNER JOIN authorlist a
ON b.book_aut=a.author_id
Try this it should work:
INSERT INTO lnk_book_author (book_fk, author_fk)
VALUES ((SELECT Id FROM books), (SELECT Id FROM authors))
And by the way there's no point having an Id column in the lnk_book_authors table, you may as well just make the foreign keys a composite primary key.
UPDATE
Sorry I realise that would only work with one record, try the following SQL:
INSERT INTO lnk_book_author (book_fk, author_fk)
SELECT books.Id, authors.Id
FROM books, authors