按备用拼写分组

时间:2014-07-17 23:16:16

标签: php mysql group-by

我有一张包含预期列的地址表(平面,房屋,街道,邮编,国家等)。

我使用PHP从表单输入($ street)执行MySQL搜索。我已成功完成了这项工作,因此我可以搜索所有道路拼写版本(例如:' street',' st',' st。'),如下所示。我希望输出数组按街道分组。以下分组按每个拼写单独列出。我的回归组有没有办法包括拼写的所有变体?

我的代码

<?php
    $results = $db->prepare(
        "SELECT * FROM entries
        WHERE 
        street = :street
        OR street = REPLACE(:street, 'st', 'street')
        OR street = REPLACE(:street, 'st.', 'street')
        OR street = REPLACE(:street, 'st.', 'st')
        OR street = REPLACE(:street, 'street', 'st')
        OR street = REPLACE(:street, 'street', 'st.')

        GROUP BY street, house
    ")

    $results->bindParam(':street', $street);
    $results->execute();

    $output = $results->fetchAll(PDO::FETCH_ASSOC);    
    return $output;
?>

当前示例输出

[1] Church Street
    [1] 12 Church Street
    [2] 25 Church Street
[2] Church St.
    [1] 19 Church St.

所需的示例输出

[1] Church Street
    [1] 12 Church Street
    [2] 25 Church Street
    [3] 19 Church St.

1 个答案:

答案 0 :(得分:0)

我认为您在where子句中尝试处理的数据中存在同样的问题。整改地址可能是一个挑战。以下是对这个小例子的尝试:

SELECT *
FROM entries
WHERE street = :street
      OR street = REPLACE(:street, 'st', 'street')
      OR street = REPLACE(:street, 'st.', 'street')
      OR street = REPLACE(:street, 'st.', 'st')
      OR street = REPLACE(:street, 'street', 'st')
      OR street = REPLACE(:street, 'street', 'st.')
GROUP BY (case when street like '%st' then concat(street, 'reet')
               when street like '% st.' then replace(street, ' st.', ' street')
               else street
          end), house;

编辑:

你应该重复group by expression in the select`条款:

SELECT (case when street like '%st' then concat(street, 'reet')
             when street like '% st.' then replace(street, ' st.', ' street')
             else street
        end) as street, house
FROM entries
WHERE street = :street
      OR street = REPLACE(:street, 'st', 'street')
      OR street = REPLACE(:street, 'st.', 'street')
      OR street = REPLACE(:street, 'st.', 'st')
      OR street = REPLACE(:street, 'street', 'st')
      OR street = REPLACE(:street, 'street', 'st.')
GROUP BY (case when street like '%st' then concat(street, 'reet')
               when street like '% st.' then replace(street, ' st.', ' street')
               else street
          end), house;