PL / SQL查找包含最多信息的项目

时间:2015-08-25 17:52:02

标签: sql oracle plsql

我有一张类似

的表格
CREATE_TABLE employees
{
    employee_id number(10),
    name varchar2(50),
    address varchar2(50)
};

我想找到最接近搜索的匹配项。我可以运行如下代码

CREATE FUNCTION FindBest (find_name int, find_address) return int IS
    id INT;

    BEGIN
        id := 0;

        BEGIN
            SELECT employee_id INTO id FROM employees WHERE name = find_name AND address = find_address;
            EXCEPTION
                WHEN NO_DATA_FOUND THEN
                BEGIN
                    SELECT employee_id INTO id FROM employees WHERE name = find_name;
                    EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                        BEGIN
                            SELECT employee_id INTO id FROM employees WHERE address = find_address;
                        END;
                END;
        END;

    return id;

END FindBest;

但是有更好的方法吗?也许是一个看起来像

的查询
SELECT employee_id INTO id FROM employees WHERE name = find_name OR address = find_address ORDER BY {Best Match} LIMIT 1;

1 个答案:

答案 0 :(得分:2)

您可以使用单个简化查询应用相同的逻辑,如下所示:

select *
  from (select *
          from employees
         where name = find_name
            or address = find_address
         order by case when name = find_name and address = find_address then 1
                       when name = find_name then 2
                       else 3
                  end)
 where rownum < 2;