Frage

I need to select only the most significant value from a table. Using Postgre SQL (last version) Follows the data sample:

Table Company

Id, Name, ExternalId, StartAt
1   Comp1      54123  21/05/2000
2   Comp2      23123  21/05/2000

Table Address

Id,  Company, Address_Type, City
1          1            7     A
2          2            2     B
3          2           62     C

Table Adress_Type

Id, Name, importance_order
62  Adt1               1
7   Adt2               2
2   Adt3               2

What i need to do is to get the company and its major Address, based on the "importance_order". There is already a function that returns this result:

Create function~~~~
Select * from Company  c
join Address a on c.address_id = a.id
Join AddressType at on a.adresstype_id = at.id
ORDER by at.importance_order
Limit 1

My problem now is that this function is called one time for every row in the query, and it take so much time (about 20 min.). Should it be possible to do this similar aproach by joinning tables? I need this join to get the First "most important"address, and then get the City name, but need to do this in a "faster" way. I need to reduce subquery`s number to its minimal.

Select * from table t
    inner join Company c on t.company_id = c.id
    left join address a on (c.company_id = c.id)
    left join addresstype at on (a.adresstype_id = at.id)
    where at.id = (
        select max(id)  from addresstype 
        where adresstype in (
            select adresstype from adress where company_id = c.id
            )
        )   

If it is not clear tell me that i get more into details.

Thanks.

War es hilfreich?

Lösung

For this you need PostgreSQL 8.4+ I suppose

SELECT T.*
FROM TABLE AS T
INNER JOIN
(
    SELECT * FROM
    (
        SELECT C1.*, ROW_NUMBER() OVER(partition by C1.ID ORDER BY T.IMPORTANCE_ORDER) AS RN
        FROM COMPANY AS C1
        INNER JOIN ADDRESS AS A
        ON C1.ID = A.COMPANY
        INNER JOIN ADDRESS_TYPE AS T
        ON T.ID = A.ADDRESS_TYPE_ID
    ) A 
    WHERE RN = 1
) AS B
ON B.ID= T.COMPANY_ID
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top