帮助SQLite(使用子查询连接表)

时间:2011-05-17 12:59:55

标签: sqlite match subquery closest

伙计们,我真的很生气这个...... 我有两张桌子:

1. UniquePrefixes
2. Operator

UniquePrefixes仅包含“前缀”字段。 例如:

Prefix
------
1
12
123
12345

'Operator'表有很多数据,包括'Prefix'字段。 例如:

..... 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
    )

但它不起作用,因为subselect首先被执行(显然):(

我希望这是有道理的,并且非常感谢任何帮助

1 个答案:

答案 0 :(得分: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