MySQL copy column from different tables, insert at top of table - mysql

I'm trying to merge a couple tables together to consolidate the data, but when I try to insert a column from one table to the other, the query I'm using inserts the records after the last currently existing record in the table. There are a ton of questions about duplicating columns, but they all seem to be starting with an empty table.
INSERT INTO newTable( newColumn ) SELECT oldColumn FROM oldTable
How do I modify this query to insert the rows at the beginning of the table instead of the end?
Visual representation of what is happening (left) vs. what I want to happen (right):
+--------+--------+------------+ +--------+--------+------------+
| ID | Column | newColumn | | ID | Column | newColumn |
+--------+--------+------------+ +--------+--------+------------+
| 1 | 12345 | | | 1 | 12345 | 12345 |
| 2 | 12345 | | | 2 | 12345 | 12345 |
| 3 | 12345 | | | 3 | 12345 | 12345 |
| 4 | | 12345 | +--------+--------+------------+
| 5 | | 12345 |
| 6 | | 12345 |
+--------+--------+------------+

As mentioned in the comments you need an UPDATE statement not an INSERT statement:
UPDATE newTable
JOIN oldTable
ON newTable.id = oldTable.id
SET newcolumn = oldcolumn;
A tested example may be seen here: http://sqlfiddle.com/#!2/77724/1

Related

SQL (MYSQL, Postgres) Lookup/report table

I'm basically making a lookup table for my three tables but its not doing what I want. Those 3 tables were created by loading 3 different csv files.
What I'm trying to do is inserting the ID's from those tables into the lookup one.
This is what I keep getting:
---------------Lookuptable---------------
|lookup_ID|Table1_ID|Table2_ID|Table3_ID|
| 1 | 1 | | |
| 2 | 2 | | |
| 3 | 3 | | |
| | | 1 | |
| | | 2 | |
| | | 3 | |
| | | | 1 |
| | | | 2 |
| | | | 3 |
What I need is:
---------------Lookuptable---------------
|lookup_ID|Table1_ID|Table2_ID|Table3_ID |
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 3 | 3 | 3 | 3 |
I kind of get why this is happening, it inserts one row bellow every time with single inserts like
insert into Lookuptable(Table1_ID) select T1id from Table1;
and the others...
But I've tried nested ones too like
insert into Lookuptable(Table1_ID, Table2_ID, Table3_ID)
select Table1.T1id, Table2.T2id, Table2.T2id from Table1, Table2, Table3;
but still doesn't work. In fact this one just crashes the Mysql server and has an endless query on Postgres. I've tried other nested examples but none worked.
I'm also using Foreign Keys which work when I manually input a new value, but since the other tables come from loaded CSV files I have to input the values already there manually.
I'm really not sure what to do.
If I understand correctly what you want something like this should work
https://www.db-fiddle.com/f/k6CGsVXazSqJDfwKkdr6S7/1
SET #i:=0,#j:=0,#h:=0;
INSERT INTO Lookuptable
SELECT NULL,t1.ID,t2.ID,t3.ID FROM
( SELECT #i:=(#i+1) AS temp_id,ID FROM Table1 ) t1
INNER JOIN
( SELECT #j:=(#j+1) AS temp_id ,ID FROM Table2 ) t2 ON t1.temp_id=t2.temp_id
INNER JOIN
( SELECT #h:=(#h+1) AS temp_id ,ID FROM Table3 ) t3 ON t2.temp_id=t3.temp_id;

Update MS Access table empty fields based on same table

In MS Access database, I'm working with a table that has rows. In some cases not all columns of the rows are filled. I want to create an update query to update the values of the empty fields with data from other rows where the column is not empty.
googled the question but no satisfying answer has been found. Can someone show me how the query should be build?
Current table looks like
| Invoicenumber | Customer | Date |
|---------------|----------|---------|
| 5 | 12 | 12-6-19 |
| 5 | | 12-6-19 |
| 5 | | 12-6-19 |
| 5 | | 12-6-19 |
| 6 | 18 | 15-6-19 |
| 6 | | 15-6-19 |
| 6 | | 15-6-19 |
| 7 | 20 | 20-6-19 |
| 7 | | 20-6-19 |
I need the table to look like this after updating:
| Invoicenumber | Customer | Date |
|---------------|----------|---------|
| 5 | 12 | 12-6-19 |
| 5 | 12 | 12-6-19 |
| 5 | 12 | 12-6-19 |
| 5 | 12 | 12-6-19 |
| 6 | 18 | 15-6-19 |
| 6 | 18 | 15-6-19 |
| 6 | 18 | 15-6-19 |
| 7 | 20 | 20-6-19 |
| 7 | 20 | 20-6-19 |
You can do it with just SQL by joining the table to itself:
UPDATE
Invoices
INNER JOIN Invoices AS Inv2
ON Invoices.InvoiceNumber = Inv2.InvoiceNumber
SET
Invoices.Customer = Inv2.Customer
WHERE
(Invoices.[Customer] Is Null)
AND (Inv2.Customer IS NOT NULL)
You can place a Switch statement into the update to choose the value to update based on the state of the CUSTOMER field.
Update TestTable
Set CUSTOMER = Switch(CUSTOMER is Null,OTHER_FIELD,CUSTOMER = '',OTHER_FIELD,CUSTOMER<>'',CUSTOMER)
This statement will update the CUSTOMER field to the OTHER_FIELD where CUSTOMER is blank or CUSTOMER is Null. If CUSTOMER has a value, it sets it to that value (essentially leaving it as the same.)
The 'SWITCH' statement is Access's version of a 'Switch' or 'Select Case' in code, where the first parameter is the condition to check, the parameter after it is the value to take if the previous condition returns true. So...
Switch(1=1,'YES',2=1,'NO', case 3, return 3, case 4, return 4, etc., etc.,)
would return the 'YES' because 1 is equal to 1.
There would be a more eloquent way to do this with code, but in an Access query, I don't know any other way.
Try using domain aggregate function to pull the Customer:
UPDATE table1 SET table1.Customer = DMax("Customer","table1","Invoicenumber=" & [Invoicenumber])
WHERE (((table1.Customer) Is Null));
Question answered by solution mentioned by #John Mo. Used his code to update table with data available within the table.

Delete duplicate records in MySql in one single query

I have this MySQL table:
+------+------+
| id | name |
+------+------+
| 1 | John |
| 1 | John |
| 2 | Jill |
| 2 | Jill |
| 3 | Jack |
| 3 | Jack |
+------+------+
Can anyone please tell me how to delete the duplicate records and keep one record from this table in MySQL in one single query (i.e without creating another table)?
You have basically two options unless you want to do something more precise:
select * from table group by ID
or, alternatively:
select distinct(ID), name from table

MySQL insert skipped IDs

I have a mysql table which has two columns, id and value.
id(auto_increment primary key)
value(varchar 255)
insert into table columns(`id`,`value`)VALUES(,'something1');
insert into table columns(`id`,`value`)VALUES(,'something2');
output
+----+---------------+
| id | value |
+----+---------------+
| 1 | something1 |
| 2 | something2 |
+----+---------------+
Now Inserting one value again
insert into table columns(`id`,`value`)VALUES(8,'something8');
Updated Table
+----+---------------+
| id | value |
+----+---------------+
| 1 | something1 |
| 2 | something2 |
| 8 | something8 |
+----+---------------+
Now I am inserting one value again
insert into table columns(`id`,`value`)VALUES(,'something');
Final Output
+----+---------------+
| id | value |
+----+---------------+
| 1 | something1 |
| 2 | something2 |
| 8 | something8 |
| 9 | something |
+----+---------------+
But I want the final output like this
+----+---------------+
| id | value |
+----+---------------+
| 1 | something1 |
| 2 | something2 |
| 8 | something8 |
| 3 | something |
+----+---------------+
Now id is 3 and further insertion will create id 4,5,6,7,9 and so on.
Is there any way to get achieve this ?
I know it is old post but mybie it will help someone :)
I am afraid it cannot be done automatically, however, I solved it to my client, maybe some of you could find it useful:
DECLARE FirstEmptyId int;
SELECT l.id +1 AS
START
FROM TableName AS l
LEFT OUTER JOIN TableName AS r ON l.id +1 = r.id
WHERE r.id IS NULL
LIMIT 1 INTO FirstEmptyId;
Insert Into TableName (Id..) Values (FirstEmptyId...)
STILL, YOU HAVE TO MIND THAT IT IS NOT ADVISABLE TO INSERT ID VALUE OTHER WAY THAN BY AUTOINCREMENT IT AND THERE IS A REASON FOR THAT :)
Consider creating the second column just for performance purposes.
Good luck fellow coders!

Mysql->autoincrementing related to an other field

I am stuck on a project design. One of the table has 1-M relation with users table. So it has a foreign key. Same field is also primary key.
Table as follows
Itemid:
Primarykey
Autoincrement
Useriditem:
Primarykey
Foreign key of id in users table
Itemname:
Not null
Values:
-----------------------------------------
| **ITEMID** | **USERID** | ITEMNAME |
-----------------------------------------
| 1 | 1 | fooooooo |
-----------------------------------------
| 2 | 1 | tinytext |
-----------------------------------------
| 3 | 1 | MediumText |
-----------------------------------------
| 4 | 2 | LARGEtext |
-----------------------------------------
| 5 | 2 | HUGETEXT |
-----------------------------------------
| 6 | 1 | BLOOOOOB |
-----------------------------------------
| 7 | 3 | 001010101 |
-----------------------------------------
This is the result of the current design. What i am wondering is that a way to make auto increment for each user separately.
Something like "Autoincrement item id GROUP BY user id"
-----------------------------------------
| **ITEMID** | **USERID** | ITEMNAME |
-----------------------------------------
| 1 | 1 | fooooooo |
-----------------------------------------
| 2 | 1 | tinytext |
-----------------------------------------
| 3 | 1 | MediumText |
-----------------------------------------
| 1 | 2 | LARGEtext |
-----------------------------------------
| 2 | 2 | HUGETEXT |
-----------------------------------------
| 4 | 1 | BLOOOOOB |
-----------------------------------------
| 1 | 3 | 001010101 |
-----------------------------------------
Is there a way to do this using mysql?
You want something like this:
Demo
CREATE TRIGGER item_id_auto_inc
BEFORE INSERT ON items
FOR EACH ROW
BEGIN
SET NEW.item_id := (SELECT CASE WHEN ISNULL(MAX(item_id)) THEN 0 ELSE MAX(item_id) END +1 FROM items WHERE user_id=NEW.user_id);
END
//
I dont know what happens when multiple users execute queries but i think i managed to narrow down the algorithm.
how to "insert into table (col1, col2) values (select max(id) from table2, select id from table3); "?
INSERT INTO table VALUES (
(SELECT (MAX(itemid)+1)
FROM table
WHERE userid = 'theid') , 'theid' , 'foo1');
Can this solve the simultaneous execution by multiple user problem.
The safer way to do this is taking into account that your application can get hit by more than 1 user at any given time
START TRANSACTION;
Insert into table A
Select Last inserted id from table A using Last_Insert_ID()
Update table B
COMMIT;
At least you are guaranteed to get this last inserted id from table A into table B.