开发者

Help with SQLite (Join tables with subquery)

Guys I am going mad with this one... I have two tables:

1. UniquePrefixes
2. Operator

UniquePrefixes contains 'Prefix' field only. Example:

Prefix
------
1
12
123
12345

The 'Operator' table have a lot of data, including a 'Prefix' field as well. Example:

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

What I am trying to achieve is:

(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

Example:

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

What I have done so far is:

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 || '%'
        )
        开发者_如何学JAVAORDER BY
            Operator.Prefix DESC
        LIMIT 1
    )

But it doesnt work since the subselect gets executed first (obviously) :(

I hope that this makes sense and will really appreciate any help


    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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜