如何在SQL中将数据从一行复制到另一行

时间:2016-07-28 19:18:27

标签: php mysql sql phpmyadmin

所以我有一个名为customers的表格,在该表格中有一些地方填写了列zip,但state列却没有。

我们可以合理地假设,如果我们有另一位客户同时填充了zipstate列,并且zip与未填充state的客户匹配,没有state填充的客户可以使其填充与其他匹配客户相同的值。

目标是在我们知道另一行时填写缺失值。

示例:

       BEFORE:                         AFTER:
/====================\         /====================\
| id | zip   | state |         | id | zip   | state |
|----|-------|-------|         |----|-------|-------|
| 0  | 12345 | FL    |   ==>   | 0  | 12345 | FL    |
| 1  | 67890 | CA    |   ==>   | 1  | 67890 | CA    |
| 2  | 67890 |       |   ==>   | 2  | 67890 | CA    |
| 3  | 12345 |       |         | 3  | 12345 | FL    |
| 4  | 10101 |       |         | 4  | 10101 |       |
\====================/         \====================/

我的问题:如何使用MySQL更新表格并填写另一行中缺少的数据?

到目前为止,我有用于查找缺失值的SQL:

SELECT * 
FROM customers 
WHERE country = 'united states' 
    AND (zip <> '' OR zip IS NOT NULL) 
    AND (state = '' OR state IS NULL)

4 个答案:

答案 0 :(得分:2)

您可以使用更新和内部联接

update my_table as a
inner join source_table as b on  a.zip = b.zip 
set a.state = b.state 
where b.state is not null
or b.state = ''
AND country = 'united states' ;

答案 1 :(得分:1)

你可以这样做:

UPDATE customers 

INNER JOIN customers AS updateValues ON updateValues.zip = customers.zip AND updateValues.state IS NOT NULL AND updateValues.state != ''

SET customers.state = updateValues.state

WHERE (customers.zip <> '' AND customers.zip IS NOT NULL) 
AND (customers.state = '' OR customers.state IS NULL)

(不确定WHERE country = 'united states'的来源,所以我删除了它)

答案 2 :(得分:1)

我不会这样做。

https://en.wikipedia.org/wiki/List_of_ZIP_code_prefixes

邮政编码的前3位数字表示它所处的状态。我会根据它做一些逻辑。

编辑:这不必太复杂

UPDATE CUSTOMERS
SET STATE = CASE
                WHEN SUBSTRING(zip, 1,3) IN ('448','449', ect....) THEN 'OH'
                ....
                ....
            END
WHERE STATE IS NULL

答案 3 :(得分:0)

不确定性能,但您应该能够:

update table_name tn1
   set tn1.state = (select max(tn2.state) from table_name tn2 where tn2.zip = tn1.zip and tn2.state is not null)
 where tn1.state is null