mySQL - 使用select返回多行来更新多个列

时间:2011-05-12 22:31:29

标签: mysql

我有一个邮政编码表,我想用3个最近的邻居更新每个邮政编码。即填写此表中的空白:

postcode  nearestPostcode1  nearestPostcode2  nearestPostcode3
_______________________________________________________________

KY6 1DA      -                -                  -
KY6 1DG      -                -                  -
KY6 2DT      -                -                  -
KY6 1RG      -                -                  -
....

我已经找到了一个SELECT查询来查找最近的邮政编码,这是第一行可以更新的一种笨拙的方式:

update table1 set 
nearestPostcode1 = (select query for returning the first nearest postcode),
nearestPostcode2 = (select query for returning the second nearest postcode),
nearestPostcode3 = (select query for returning the third nearest postcode)
where postcode = 'KY6 1DA';

但是,这将导致为每个行更新运行3个选择查询。如果有一些方法可以做这个伪代码所表达的内容,那将会更有效率:

update table1 set 
(nearestPostcode1, nearestPostcode2, nearestPostcode3) = 
(select query to return the 3 nearest postcodes)
where postcode = 'KY6 1DA';

上面的“选择查询”如下所示:

select postcode from postcodeTable 
order by <equation to calculate distance> ASC 
limit 3

无论如何,将select返回的行放入可用于更新多个字段的表单中吗? 感谢。

4 个答案:

答案 0 :(得分:11)

Update Table1
    Cross Join  (
                Select Min( Case When Z1.Num = 1 Then Z1.postcode End ) As PostCode1
                    , Min( Case When Z1.Num = 2 Then Z1.postcode End ) As PostCode2
                    , Min( Case When Z1.Num = 3 Then Z1.postcode End ) As PostCode3
                From    (
                        Select postcode 
                            , @num := @num + 1 As Num
                        From postcodeTable 
                        Where postcode = 'KY6 IDA'
                        Order By <equation to calculate distance> ASC 
                        Limit 3
                        ) As Z1
                ) As Z
Set nearestPostCode1 = Z.PostCode1
    , nearestPostCode2 = Z.PostCode2
    , nearestPostCode3 = Z.PostCode3
Where Table1.postcode =  'KY6 IDA'

答案 1 :(得分:2)

你可以做类似的事情:

UPDATE table1
SET
nearestPostcode1 = pc1,
nearestPostcode2 = pc2,
nearestPostcode3 = pc3
FROM 
(SELECT pc1, pc2, pc3 FROM ....) t
WHERE 
postcode = 'KY6 1DA';

我在Stackoverflow上发现了关于如何将列转换为行的相关问题:

  

MySQL - Rows to Columns

在您的情况下,您可以执行类似

的操作
SELECT 
IF(@rownum=1,postcode,'') ) AS pc1, 
IF(@rownum=2,postcode,'') ) AS pc2, 
IF(@rownum=3,postcode,'') ) AS pc2, 
FROM
(SELECT postcode 
FROM postcodeTable 
ORDER BY <equation to calculate distance> ASC 
LIMIT 3)

这是一个模拟MySQL [1]中的ROW_NUMBER()功能的黑客攻击:

SELECT @rownum:=@rownum+1 rownum, t.*
FROM (SELECT @rownum:=0) r, mytable t;

答案 2 :(得分:0)

我认为您可以使用伪代码执行此操作:

REPLACE INTO table1 (postcode, nearestPostcode1, nearestPostcode2, nearestPostcode3)
    SELECT "KY6 1DA", col1, col2, col3 FROM myTable WHERE ...;

指定真正的SQL会更容易。

请注意,第一列在引号中指定为常量。要实现此目标,postcode必须是UNIQUEPRIMARY索引。

答案 3 :(得分:-1)

任何时候我看到一个表格,其列名在他们的名字后面都有1-up计数器,我很担心。

通常,存储可以从已存储的数据计算的数据是坏想法(TM)。如果您的应用程序突然需要 4 最近的邮政编码,会发生什么?如果邮政编码边界改变了怎么办?

假设距离计算不是很复杂,那么从长远来看,你最好不要明确地存储这些数据。