使用子查询非关系表进行更新

时间:2016-04-30 17:29:00

标签: mysql sql subquery

我有以下sql查询,但是当我执行时它给我一个消息错误:Unknown column 't1.ip' in 'where clause'。 如果我在子查询中对t1.ip进行硬编码只是为了测试,那就完美了。

UPDATE
    report_a t1,
    (SELECT
        location.country, region.name, location.city
    FROM
        geoip
    INNER JOIN
        location
    ON
        geoip.locId = location.locId
    INNER JOIN
        region
    ON
        region.country = location.country
    AND
        region.region = location.region
    WHERE
        INET_ATON(t1.ip) BETWEEN startIpNum AND endIpNum
    LIMIT 1) AS t2
    SET
        t1.country = t2.country,
        t1.city = t2.city,
        t1.state = t2.name;

有人知道如何进行此查询吗?

由于

1 个答案:

答案 0 :(得分:0)

您正在寻找join。关于LIMIT 1应该做什么,我有点不清楚。我把它移到外部查询中,虽然这可能不正确:

UPDATE report_a t1,
       (SELECT location.country, region.name, location.city, startIpNum, endIpNum
        FROM geoip INNER JOIN
             location
             ON geoip.locId = location.locId INNER JOIN 
             region
             ON region.country = location.country AND
                region.region = location.region
       ) glr
       ON INET_ATON(t1.ip) BETWEEN glr.startIpNum AND glr.endIpNum
    SET t1.country = t2.country,
        t1.city = t2.city,
        t1.state = t2.name
    LIMIT 1;

在我考虑它时,你可能不想要LIMIT 1。为什么子查询会有多个匹配?