由于子查询,查询速度极慢

时间:2015-09-20 22:07:15

标签: postgresql

我正在尝试将一些数据移植到新的结构中,但它会永远带我。

查询如下:

INSERT INTO atemp_addresses (id, city, state, country_id)
SELECT id, (SELECT name from cities WHERE id=adr.city_id limit 1),
(SELECT name FROM states WHERE id=(SELECT state_id FROM cities WHERE id=adr.city_id limit 1) limit 1), (SELECT country_id FROM states WHERE id=(SELECT state_id FROM cities WHERE id=adr.city_id limit 1) limit 1), FROM addresses adr

因为数据保存在其他表中,所以我必须使用所有这些子查询,这会大大减慢它的速度。有更快的方法吗?

1 个答案:

答案 0 :(得分:2)

这是您的查询:

INSERT INTO atemp_addresses (id, city, state, country_id)
    SELECT id,
           (SELECT name from cities WHERE id = adr.city_id limit 1),
           (SELECT name FROM states WHERE id = (SELECT state_id FROM cities WHERE id=adr.city_id limit 1) limit 1),
           (SELECT country_id FROM states WHERE id=(SELECT state_id FROM cities WHERE id=adr.city_id limit 1) limit 1)
    FROM addresses adr;

反复地,您使用LIMIT而没有ORDER BY。这意味着您将获得一个可以从一次调用更改为下一次调用的任意匹配行。

等效查询应为:

INSERT INTO atemp_addresses (id, city, state, country_id)
    SELECT adr.id, c.name, s.name, s.country_id
    FROM addresses adr JOIN
         cities c
         ON adr.city_id = c.id JOIN
         states s
         ON c.state_id = s.id;

您对LIMIT的使用表明可能有多个城市具有相同的id(数据库设计不佳的迹象?)。如果是这样的话:

INSERT INTO atemp_addresses (id, city, state, country_id)
    SELECT DISTINCT ON (adr.id) adr.id, c.name, s.name, s.country_id
    FROM addresses adr JOIN
         cities c
         ON adr.city_id = c.id JOIN
         states s
         ON c.state_id = s.id 
    ORDER BY adr.id;