每个结果有多个子查询,如何更快?

时间:2017-03-15 08:25:09

标签: python sql postgresql psycopg2 postgresql-9.5

我正在做这样的查询:

select
    m.monster_name,
    case when count(a.ability_id) = 0 then null else count(a.ability_id) end as `count`
from monster m
left join monster_ability ma on m.monster_id = ma.monster_id and ma.used is null
left join ability a on ma.ability_id = a.ability_id
group by m.monster_id

然后对于每个人,我都会获取他们的车辆信息:

cursor.execute(
    '''
    SELECT person.id, person.name
    FROM person
    JOIN vehicle ON vehicle.owner_id = person.id
    WHERE person.age >= 18 AND vehicle.model = %s
    ''',
    ('Toyota Auris',)
)
people = [dict(row) for row in cursor.fetchall()]

但是这辆车非常慢,因为我有超过100万人和10万辆车登记。有没有办法让第二个查询更快?

所以我想要的是拥有与特定车型匹配的车辆的所有for person in people: cursor.execute( ''' SELECT vehicle.id AS id, vehicle.name AS name, vehicled.model AS model FROM vehicle JOIN person ON person.id = vehicle.owner_id WHERE person.id = %s ''', (person['id'],) ) person['vehicles'] = [dict(row) for row in cursor.fetchall()] 物品,以及车辆的所有,无论车辆的型号如何。

2 个答案:

答案 0 :(得分:2)

你可以尝试首先获取拥有丰田Auris的人然后在车辆上进行双重加入。所有这些都适合一个查询。

的内容
SELECT v1.id, person.id AS pid, v2.id AS vid v2.model AS model FROM vehicle AS v1 JOIN person ON v1.owner_id = person.id JOIN vehicle AS v2 ON v2.owner_id = person.id WHERE person.age >= 18 AND v1.model = 'Toyota Auris';

答案 1 :(得分:0)

尝试:

 cursor.execute(
    '''
    SELECT person.id, person.name
    FROM person
    WHERE person.age > 17
    '''
)
people = [dict(row) for row in cursor.fetchall()]

 for person in people:
    cursor.execute(
        '''
        SELECT vehicle.id AS id, vehicle.name AS name, vehicled.model AS model
        FROM vehicle
        WHERE vehicle.owner_id= %s and vehicle.model = %s
        ''',
        (person['id'],'Toyota Auris',)
    )
    person['vehicles'] = [dict(row) for row in cursor.fetchall()]