简体   繁体   中英

Mysql Update from another table by column name

I have two tables that look like this

Name:

name        gender   babies   year    age   prob
Mary        F         16707   1900    0 
Helen       F          6343   1900    1 
Anna        F          6114   1900    114   
Margaret    F          5306   1900    6 
Ruth        F          4765   1900    114   
Elizabeth   F          4096   1900    114   

LT

age 1900    1901    1902    1903
0   0.1460  0.1434  0.1408  0.1382
1   0.1740  0.1706  0.1672  0.1638
2   0.1875  0.1837  0.1799  0.1761
3   0.1960  0.1921  0.1882  0.1842
4   0.2031  0.1989  0.1948  0.1906
5   0.2081  0.2038  0.1995  0.1952
114 0.2117  0.2074  0.2030  0.1986

I am trying to do an update statement for the 'Name' table in the 'prob' field. So it will be looking at age and year from the name table and compare it to the LT table looking at a where the column = year and age = age.

Is this possible to search where a value equals a column name?

The basic idea that I have looks like this:

update name t1, lt t2
set t1.prob = t2."?????"
where 
t1.age = t2.age

So for the tables above it would look like this

name        gender   babies   year    age   prob
Mary        F         16707   1900    0 0.1460
Helen       F          6343   1900    1 0.1740
Anna        F          6114   1900    114   0.2117
Margaret    F          5306   1900    5 0.2081
Ruth        F          4765   1900    114   0.2117
Elizabeth   F          4096   1900    114   0.2117

Your Question isn't clear. I will make a few assumptions. As Omer Iqabl rightly pointed out your tables do not agree.

To make the tables agree the second table must be changed to :

age | year | weight
-------------------
0    1900    0.1460

etc...

this will allow you to query your tables and join them.

UPDATE name AS a 
SET prob = (SELECT weight 
        FROM lt AS b 
        WHERE b.year = a.year AND b.age = a.age
       );

The above query I hope helps. IT updates the prob column from where the years in lt and name agree, and where the ages in lt and name agree.

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM