SQL,将“SELECT”结果列表传输到另一个表中

时间:2013-07-08 06:59:54

标签: mysql sql database

我现在有三张桌子。

agare (owner)

===================================================================================================
| FNR   |FASTIGHETSBETECKNING|     NAMN      |  CO  |UTADR1|    UTADR2      | POSTNR    | POSTORT |
===================================================================================================
|854684 |     Berryfarm 1    | Granny Smith  | NULL | NULL | Treebranch 12  | 765 18    |  Meadow |
|135864 |     Satinfarm 1    | Sara Lovelace | NULL | NULL | Satin Hill 12  | 376 49    |  Satina |
|468952 |     Fairyhill 7    | Paula Green   | NULL | NULL |  Oaktree 12    | 468 67    |  Fairys |
|468952 |     Fairyhill 6    | Paula Green   | NULL | NULL |  Oaktree 12    | 468 67    |  Fairys |

fastighet (Estate that the owner owns)
===============================================================
| FNR  |FASTIGHETSBETECKNING|BELAGENHETSADRESS|POSTNR|POSTORT |
---------------------------------------------------------------
|854684|     Berryfarm 1    |  cherryroad 14  |759 45|Grassmow|
|135864|     Satinfarm 1    |  Satineroad 69  |136 89|Satiniqe|
|468952|     Fairyhill 7    |  fairysroad 17  |845 97|Birdsfal|
|468952|     Fairyhill 6    |  fairysroad 19  |962 63|Flowersy|
===============================================================

users (registrated user)
========================
|username|   adress    |
------------------------
| 854684 |             |
| 135864 |             |
| 468952 |fairysroad 17|
| 468952 |fairysroad 19|
========================

我可以找到一个拥有一个庄园的人:

SELECT FNR FROM agare,users WHERE FNR IN (SELECT FNR FROM fastighet, users WHERE FNR=username AND adress IS NULL GROUP BY FNR HAVING COUNT(FNR) < 2) AND users.username=FNR GROUP BY FNR

女巫使用地址字段空白的男性人员返回列表

但我想用fastighet的数据填充用户的空白地址字段。

我尝试使用INSERT into users (adress) SELECT "something",但我需要帮助

关心马丁

2 个答案:

答案 0 :(得分:0)

您可以尝试使用fastighet表的值在users表上运行UPDATE,类似于以下内容:

UDPATE a
SET address = b.FASTIGHETSBETECKNING
FROM users a
JOIN fastighet  b on a.username = b.fnr
WHERE a.address is null OR a.address = ''

答案 1 :(得分:0)

我仍然在努力理解你的问题,但可能是你在更新后而不是插入?

请参阅sqlfiddle

我使用fastighet表的地址更新了users表,其中每个FNR只有一个条目。我明白了吗?

UPDATE users u INNER JOIN (SELECT * FROM fastighet GROUP BY FNR HAVING COUNT(*) = 1) f 
ON u.username = f.FNR
SET u.adress = f.BELAGENHETSADRESS;