1
votes

I have one table that has a non unique identifier and I need to update a corresponding column with a value from another table with a unique identifer.

Essentially I have two tables

Table1

| Col1 | Col2 |
---------------
|  A   |  1   |
---------------
|  A   |  2   |
---------------
|  B   |  4   |
---------------
|  C   |  6   |
---------------
|  C   |  9   |
---------------

Table2

| Col1 | Col2 |
---------------
|  A   |  1   |
---------------
|  B   |  2   |
---------------
|  C   |  3   |
---------------

I want to perform a calculation on Table1.Col2 with the corresponding values from Table2.Col2 where Table1.Col1 = Table2.Col1 using MySQL.

For Example:

| Col1 | Col2 |
---------------
|  A   |  1   | // (1/1)
---------------
|  A   |  2   | // (2/1)
---------------
|  B   |  2   | // (4/2)
---------------
|  C   |  2   | // (6/3)
---------------
|  C   |  3   | // (9/3)
---------------

Any help would be appreciated.

3
Is Col1 unique in Table 2? If not which value do you wish to use?Jim

3 Answers

3
votes

It looks like you need something like this:

UPDATE Table1
    JOIN Table2
        ON Table1.Col1 = Table2.Col2
SET Table1.Col2 = Table1.Col2/Table2.Col2
3
votes

Join the tables and use the arithmetic operator /

select Table1.Col2 / Table2.Col2 as result
from Table1 
inner join Table2 on Table1.Col1=Table2.Col2;
1
votes

You can do the following:

// for an update
update table1 
join table2 
    on table1.col1 = table2.col1
set table1.col2 = (table1.col2 /table2.col2)

// for a select 
SELECT (t1.col2 /t2.col2) as results
from table1  t1
join table2 t2
    on t1.col1 = t2.col1