Inserting values into a third table by CROSS JOINing two tables - mysql

I want to insert values into a Table_C by cross joining two tables Table_A and Table_B.
Table_A contains two attributes ID and item.
Table_B contains two attributes ID and color.
Table_C contains four attributes ID,item,color,quantity.
All IDs have AUTO INCREMENT.
suppose each item can have all color and I need to create a relation about it.
How should I write a query for this? How could I reference a relation cross joining item and color.
What my solution is create an intermediate third table joining these two tables and then use that table to insert values into Table_C. But I am pretty sure that there is a better optimized solution for this.
Thanks in advance.

No need for a temp table... You can do:
insert into ...
select ... from ...
Write the query you'd need to "fill" that temp table you mention, and insert the rows directly into your final table.

Here is the query which worked for me.
INSERT INTO Table_C (SELECT null, Table_A.item, Table_B.color, null FROM
Table_A CROSS JOIN Table_B);

Related

How do I migrate and sync up a table efficiently?

I have a table A, it has millions of records and it's growing. A new column needs be added to table A with indexing, but it could be headache to migrate such a large table. So table B is created at some point from table A, question is how to sync up these 2 tables efficiently?
There're multiple scenarios new records will be added to table A.
To 'Sync' up two tables without actually merging them you can create a UNION VIEW. A VIEW can be used just like a table for calculation, manipulation, data storage etc. This is assuming that both tables have the same amount of rows, if not you'll need to create primary and foreign keys.
CREATE OR REPLACE VIEW viewname AS
SELECT * FROM TABLE_A
UNION ALL
SELECT * FROM TABLE_B
Now if both tables don't share the same amount of rows you'll need at least 1 field in common between the two tables called primary and foreign keys, to join the tables using the primary and foreign keys you'll need to use a JOIN like this:
CREATE OR REPLACE VIEW viewname AS
SELECT TableA.FieldName, TableB.FieldName, TableA.FieldName
FROM TableA
LEFT JOIN TableB
ON TableA.primarykeyField = TableB.foreignkeyField
UNION ALL
SELECT TableA.FieldName, TableB.FieldName, TableA.FieldName
FROM TableA
RIGHT JOIN TableB
ON TableA.primarykeyField = TableB.foreignkeyField
It depends on what type of join you want but I think FULL JOIN will give you the best results, FULL JOIN's aren't supported in MySQL but using LEFT JOIN RIGHT JOIN and UNION ALL mimics the same results.
Or if you simply want to copy all the records from table A to table B you could use this.
INSERT INTO TableB
SELECT * FROM TableA;

[MySQL]Populate a column depending on the value of different column which is a foreign key.

I have two tables TableA and TableB.
TableA(acolumn1,acolumn2,abcolumn(primarykey))
TableB(abcolumn,bcolumn1,acolumn1).
TableA is a static table where there will be no insertions or deletions.
When inserting values in TableB
insert into TableB (abcolumn,bcolumn1) values("val1","val2");
The third column in TableB(acolumn1) should be filled automatically from the TableA depending on TableB(abcolumn).
Wanted to know If i can create TableB with a similar query below.
create table TableB(abcoulmn datatype,bcolumn1 datatype,acolumn1 datatype Set TableA.acolumn1 where abcolumn=TableA.abcolumn)
The above query is wrong and it is just to make people understand what i require.
Thanks in Advance.

Map Values from Column in Table A to Corresponding Column in Table B

Part 1:
In MySQL suppose I have Table A which has more columns than Table B. I want to transfer values from Table B to Table A where the id row in A matches the id Row in B and update the values in table A from the values in table B.
Part 2:
Table B is a superset of table A, so how does one insert ids and their corresponding values from table B into table A while also updating id's that are in table A.
Like FreshPrinceOfSO already mentioned in the comments, you won't get code for free here.
But here are at least the steps. Two possibilities. Either you split the work up in two statements, one update then one insert statement. Or you could work with
INSERT ... ON DUPLICATE KEY UPDATE ...
You would have to have an unique index on the table for this to work.
For the first solution mentioned you'd inner join the tables for the update first, that's trivial. Then for the insert you'd use a select with a left join and with is null checking for entries that are not already in the table.
Good luck...

Syncing primary key between two tables stored in two different database

I have two MySQL database that contain two table, let's call them TABLE_A and TABLE_B. Both these tables have as fields id and title. Both databases are on the same server and the same user can access both.
Now, TABLE_A is a subset of TABLE_B for what concern the title field. It means that every title in TABLE_A is present in TABLE_B, too. While id fields of the two table are in no way related.
What I need is to sync id fields in TABLE_A with id fields in TABLE_B, according to the title, i.e. same title, same id. If it's not clear, I have to save TABLE_B id and override TABLE_A ones. And I DON'T have to add missing title from TABLE_B to TABLE_A.
Someone suggested to use a temporal table where to copy all TABLE_B fields in common with TABLE_A and then rename it as TABLE_A. I cannot follow this way, as TABLE_A actually has also other fields that I need to maintain. So, I cannot entirely drop the old TABLE_A.
Moreover, id is the primary key for both tables. It means that I cannot simply copy from TABLE_B to TABLE_A as the query will fail as soon as I try to change one id to another one that is already present in TABLE_A but linked to a different title.
I know how to write a Perl or PHP script to do it, but I would like to know if a pure MySQL solution exists.
You can do this
CREATE TABLE TableA_TMP AS
SELECT * FROM TableA;
ALTER TABLE TableA_TMP ADD id_new int;
UPDATE TableA_TMP A INNER JOIN TableB B ON lower(A.title) = lower(B.title)
SET id_new = B.id;
RENAME TABLE TableA TO TableA_backup;
CREATE TableA AS
select id_new as id, title,.... from TableA_TMP;

SQL Optimization - Join different tables based on column value

I have a table that contains a column that acts as a "flag" which is used to decide which table to pull additional information from (i.e. the value 1 pulls from table1, 2 from table2, etc). Usually I would just join the table using indexes/keys. However the table that I could join contained information that could be normalized into separate tables which leaves me to this situation of using a column to decide which table to join.
So here is my question, what is the most efficient way to join different tables based on the value produced in this column?
Here are the two ways I know how to accomplish this task currently. I am pretty sure they are both not the optimal solution:
Pull the information from my main table (containing the column value that decides which table to join), and then through code in my application send additional queries to get the rest of the information.
Go join crazy, return the columns of every table (even if unused). Then, through my code, ignore the nulls of the tables not needed.
Definately not option 2. If you dont need the data dont retrieve it. Simple. It would be incredibly inefficient to join on tables (especially large ones) when you dont need the data. You could go with option 1 or use dynamic SQL to build up the query. I would then put some test cases together and run the execution plan to see how your query is performing.
Depending on the content of the other tables, I'd suggest a UNION - the columns returned need to be the same from each query. So you can do something like:
SELECT table1.title, tabel2.text FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE table1.key='2'
UNION
SELECT table1.title, tabel3.text FROM table1 INNER JOIN table3 ON table1.id=table3.id WHERE table1.key='3'
(Tweaking the SQL to make sure that it matches your schema, and indeed to avoid any mistakes I've added in)
I think it is possible:
create table a (id integer, flag boolean);
create table b (id integer, value_b varchar(30));
create table c (id integer, value_c varchar(30));
insert into a values (1, true), (2, false);
insert into b values (1, 'Val 1'), (2, 'Val 2');
insert into c values (1, 'C 1'), (2, 'C 2');
select a.id,
case when a.flag then b.value_b else c.value_c end AS value
from a
left join b using (id)
left join c using (id);
You can try it out.
Of course there're limitations:
number of columns is fixed, so you should go for NULLs if some values should be omitted;
you'll have to write a CASE ... END for each column;
you should know all joined tables in advance;
performance might not be the best.