2011-05-17 41 views
0

夥計們,我要瘋了這一個... 我有兩個表:幫助使用SQLite(加入表與子查詢)

1. UniquePrefixes 
2. Operator 

UniquePrefixes包含「前綴」只有場。 實施例:

Prefix 
------ 
1 
12 
123 
12345 

的「操作者」表具有大量的數據,包括「前綴」字段爲好。 例子:

..... Prefix ...... 
----- ------ ------ 
     1 
     12 

我想實現的是:

(pseudo) 

foreach unique 'prefix' 
select the 'Prefix' from 'Operator' if is equal to a unique 'prefix' 
OR 
select the 'closest' match that fits into that 

例子:

unique prefix = 1 (exists on 'Operator' so I am fine) 
unique prefix = 12345 (doesnt exist on 'Operator' so I must get '12') 

我所做的到目前爲止是:

SELECT 
    * 
FROM 
    UniquePrefixes 
LEFT OUTER JOIN Operator 
on 
    Operator.Prefix =(
     SELECT 
      Operator.Prefix 
     FROM 
      Operator, 
      UniquePrefixes 
     WHERE 
      length(Operator.Prefix)<= UniquePrefixes.prefix 
     AND UniquePrefixes.prefix LIKE(
      Operator.Prefix || '%' 
     ) 
     ORDER BY 
      Operator.Prefix DESC 
     LIMIT 1 
    ) 

但它不工作ķ因爲子查詢被執行第一(顯然):(

我希望這是有道理的,並非常感謝所有幫助

回答

1
SELECT UniquePrefixes.Prefix, Operator.Prefix 
     FROM UniquePrefixes 
LEFT JOIN Operator ON UniquePrefixes.Prefix LIKE Operator.Prefix || '%' 
        AND length(Operator.Prefix) <= length(UniquePrefixes.prefix) 
    ORDER BY length(Operator.Prefix) desc