I have two mysql tables:
table 1:
id name type
1 a 123
2 b 125
table 2:
id text
1 test1
2 test2
these two tables need to be merged into a third table
table3:
id name type text
The id is an auto increment id. the first two tables have data that are not related. I mean, row for id=1 in table 1 has nothing to do with the row for id=1 in table two. So, I basically want to write a sql script which would insert values into table 3 to look like this in the end:
table3:
id name type text
1 a 123
2 b 125
3 test1
4 test2
the ids in the old tables and the new table don't have to match. Just the data from the tables need to be in the new table.
I am very new to mysql and if anyone can help me with this, it would be great!
thanks!
It can be done with something like this:
CREATE TABLE Table3 (
id int auto_increment,
name ...,
type int,
text ...,
PRIMARY KEY (id)
);
INSERT INTO table3 (name, type, text)
SELECT name, type, text FROM (
SELECT name, type, NULL AS text FROM table1
UNION ALL
SELECT NULL as name, NULL as type, text FROM table2) AS t
With auto-increment, we don't need to recount id at all.
Here's an SQL Fiddle for you to play with. )
I actually didn't understand what empty space in your scheme was for, and assumed it's all NULLs. If not, you can just replace NULL in this query with whatever default values you'd like.
Since nothing's related, start with #raina77ow's table, but just use two queries:
INSERT INTO table3 (name, type, text)
SELECT name, type, NULL
from table1;
INSERT INTO table3 (name, type, text)
SELECT NULL, NULL, text
from table2;
Related
I've got the following table:
productId price
1 price_value1
2 price_value2
3 price_value3
I would like to insert a new product into the table and assign it a new productId. In this case its value equals to 4.
So I want my new table to look like so:
productId price
1 price_value1
2 price_value2
3 price_value3
4 price_value4
So as far as I understand, in order to do that I have to somehow retrieve the max value of productId and insert it using INSERT INTO mytable VALUES (productId + 1, price_value4).
But how do I find out the maximum value of productId?
I tried INSERT INTO mytable VALUES (SELECT MAX(productId) + 1 FROM mytable, price_value4) but it didn't work.
This should Work:
Select the max(productID) and price_value4 as a columns from mytable and insert the result.
INSERT INTO mytable (SELECT MAX(productId) + 1, 'price_value4' FROM mytable);
However, if you are not going to jump some number you can just add an auto increment id key to product_id and then you will have only to insert the price, the product ID will be incremented automatically..
This will do so :
ALTER TABLE mytable
MODIFY COLUMN `productId` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
you can change INT(10) with the INT(5) for example depanding on the size you want to give to your productId column
EDIT :
In return to the OP question in comments why his solution wouldn't work
Some suggetions says you have to make the SELECT statment in insert always between parenthesis
INSERT INTO mytable VALUES ( (SELECT MAX(ID)+1 FROM mytable) , price_value4)
.. In my Case it Return
(1093): You can't specify target table
'mytable' for update in FROM clause
AND HERE IS WHY (Quoting From the documentation)
When selecting from and inserting into the same table, MySQL creates
an internal temporary table to hold the rows from the SELECT and then
inserts those rows into the target table. However, you cannot use
INSERT INTO t ... SELECT ... FROM t when t is a TEMPORARY table,
because TEMPORARY tables cannot be referred to twice in the same
statement
BUT there is away to overcome by using a query instead of the table itself in the FROM, which has the effect of copying the requested table values instead of referencing the one that you are updating..
INSERT INTO mytable VALUES (
(SELECT MAX(ID)+1 FROM (SELECT * FROM mytable ) as mytmp ),
'price_value4');
OR (Quoting From the documentation)
To avoid ambiguous column reference problems when the SELECT and the
INSERT refer to the same table, provide a unique alias for each table
used in the SELECT part, and qualify column names in that part with
the appropriate alias.
INSERT INTO mytable Values ( (SELECT MAX(ID)+1 FROM mytable as mytmp) , 'price_value4')
This is a duplicate question. In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows.
A simple syntax to create table
CREATE TABLE Product (
productId MEDIUMINT NOT NULL AUTO_INCREMENT,
price INT NOT NULL,
PRIMARY KEY (productid)
);
While inserting supplied default or leave column as blank or supplied value as NULL. Take a look at below code snippet.
INSERT INTO Product (price) VALUES
('10'),('20'),('4'),
('30');
refer this link
I need to transfer the data of 2 tables into the new table, here is the simplified table.
Table 1
user_id_slot_1 | user_id_slot_2 | some_column | some_column_2
Table 2
user_id_slot_1 | user_id_slot_2 | some_column | some_column_2
Note:
Data from table 1 and 2 that I need to transfer/copy is almost identical.
user_id_slot_1 and user_id_slot_2 either one of them should be
empty/null.
Column's names are different from the actual database.
New Table
id | user_id | some_column | some_column_2
How can I transfer the data from Table 1 and 2?
How can I merged the column user_id_slot_1 and user_id_slot_2 into one and transfer it to user_id.
UPDATE:
I do not need to transfer/copy the ids of the Table 1 and 2, New Table needs to auto increment it.
Assuming that the new table already exists, you can use INSERT INTO ... SELECT to move the data. I have used UNION ALL here under the assumption that you don't want to remove duplicates between the two source tables should they occur.
INSERT INTO new_table (`user_id`, `some_column`, `some_column_2`)
SELECT COALESCE(user_id_slot_1, user_id_slot_2),
some_column,
some_column2
FROM table1
UNION ALL
SELECT COALESCE(user_id_slot_1, user_id_slot_2),
some_column,
some_column2
FROM table2
Notes: The COALESCE(user_id_slot_1, user_id_slot_1) term in the above query will choose user_id_slot_1 if it be not NULL otherwise it will choose user_id_slot_2. This should be fine assuming that one and only one will be non NULL for every record.
Assuming that the new_table table has its id column set to auto increment, then MySQL will handle assigning these values for you. All you need to do is omit a value for id in new_table and MySQL will handle the rest.
You should create the new table using something like this:
CREATE TABLE new_table (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
some_column VARCHAR(50) NOT NULL,
some_column_2 VARCHAR(50) NOT NULL
)
Is this what you want?
create table3 as
select id, coalesce(user_id_slot_1, user_id_slot_2) as user_id,
some_column, some_column_2
from table1
union all
select id, coalesce(user_id_slot_1, user_id_slot_2) as user_id,
some_column, some_column_2
from table2;
i got 2 tables that i want to combine its data.
the id is my key field (incremental and distinct).
table 1 and table 2 field description for example:
id - name - value
i want to insert all of table 2 data into table 1, they have different data but in some rows the same id.
so when i try to:
INSERT INTO ladatabase.table2 SELECT * from ladatabase.table1;
i get duplicate entry error.
please help me to suggest how can i solve it and combine the data with different id values for the new data.
Alex.
here are 2 ways:
first you can use if the id AUTO INCREMENT
INSERT INTO ladatabase.table2
SELECT '', name, value from ladatabase.table1;
or you find the first free ID and add it
INSERT INTO ladatabase.table2
SELECT id+555 , name, value from ladatabase.table1;
No insert all fields (exclude 'id'-field from SELECT):
INSERT INTO ladatabase.table2 SELECT name,value from ladatabase.table1;
You need to copy all but the ID column, and it will assign new IDs. You need to list all the other columns explicitly. Leaving out the ID column will cause it to get its default value, which are sequential IDs for an auto_increment field.
INSERT INTO table2 (col2, col3, col4, ...)
SELECT col2, col3, col4, ...
FROM table1
I have a MySQL database with 9 tables, each table has an id with primary key set and auto increment and a row for data, one table let's call it 'X' from this database has also a primary key and one row for data and all primary keys from other tables as foreign keys, the question is can I insert into 'X' table not by id of other tables but by data row, for example some other tables has id -> 3 and data: apple , can I insert 'apple' that takes id 3, instead of id 3 that takes apple from data row ?
You can select and insert values in one step:
INSERT INTO X (fruit_id, ...)
VALUES ((SELECT fruit_id FROM fruits WHERE fruit = 'apple'), ...);
That will insert the fruit_id of apple.
Based on i486s comment, you can also directly insert a select result:
INSERT INTO X (fruit_id, tableb_id, tablec_id, datafiled)
SELECT fruit_id, b.tableb_id, c.tablec_id, 'some data'
FROM fruits a, tableb b, tablec c
WHERE a.fruit = 'apple',
AND b.tableb_data = 'some data from tableb'
AND c.tablec_data = 'some data from tablec';
No, mysql is no ms access where you could do this. You can implement an import function in mysql or even a GUI in another programming language that translates the value 'apple' into the foreign key of 3 by looking it up in the other table. That's exactly what ms access does in the background for you.
i am looking for the query, deletes the all duplicate values.
Example Table:
1 ABC
2 BBB
3 DAC
4 ABC
5 AAA
6 ABC
output required
1 ABC
2 BBB
3 DAC
5 AAA
thanks for your help, i Google it can't find exact solution.
If you want to do an actual DELETE operation of the duplicate values (while retaining the values having the lowest id), you can do it with the multiple table DELETE syntax:
DELETE a FROM tbl a
LEFT JOIN
(
SELECT MIN(id) AS id, name
FROM tbl
GROUP BY name
) b ON a.id = b.id AND a.name = b.name
WHERE b.id IS NULL
See a demonstration of the DELETE operation
See #fvu answer here : https://stackoverflow.com/a/11249235/1166147
You can create a unique index that will remove duplicates and prevent future dupes all at once (MySQL 5.1 or higher):
ALTER IGNORE TABLE 'YOURTABLE'
ADD UNIQUE INDEX somefancynamefortheindex (Col1ID, Col2)
Assuming Tab is the name of your table containing duplicates, create a temporary table Tab_TMP with the same structure of Tab.
-- assuming `Tab` has same schema
CREATE TABLE Tab_TMP (
id INT(2) PRIMARY KEY,
name VARCHAR(8)
);
Fill Table_TMP with all Table entries.
INSERT INTO Tab_TMP(id, name) SELECT id, name FROM Tab;
Delete entries from Table.
DELETE FROM Tab;
Insert in Table entries from Table_TMP using SELECT DISTINCT.
INSERT INTO Tab(name) SELECT DISTINCT name FROM Tab_TMP;
load distinct data in a file and delete or drop your table
SELECT DISTINCT col1,col2,col3,..coln FROM table name INTO OUTFILE 'yourFilePathWIthFileName'
eg:
SELECT DISTINCT username,usernumber,usersalary,dateOFJoining,timeofJoining,datetimeOfJoining FROM asdf INTO OUTFILE 'C:/Users/ahmed.m/Desktop/modify.txt';
create your table structure laod data back from file
LOAD DATA INFILE 'yourFilePathWIthFileName' INTO TABLE tableName
eg:
LOAD DATA INFILE 'C:/Users/ahmed.m/Desktop/modify.txt' INTO TABLE asdf