带分组依据和交叉列比较的SQL(PHP)

时间:2018-12-09 12:00:41

标签: php mysql sql

我有一个MySQL表:

+======+=========+============+======+======+
| name | surname | other_name | year | date |
+======+=========+============+======+======+
| John |   Foo   |    NULL    | 2000 | 2017 |
+------+---------+------------+------+------+
| John |   Foo   |    Bar     | 2000 | 2018 |
+------+---------+------------+------+------+
| John |   Bar   |    NULL    | 2000 | 2018 |
+------+---------+------------+------+------+
| John |   Bar   |    Bar     | 2000 | 2018 |
+------+---------+------------+------+------+
| John |   Foo   |    NULL    | 1990 | 2018 |
+------+---------+------------+------+------+

我正在尝试将同一个人的记录分组。 通过出生的namesurnameyear 可以识别同一人。

但是,一个人可以更改其姓(Foo-> Bar)。然后,应使用新名称更新旧行的other_name列。不幸的是,我的数据不完整,当一个人更改名字时,other_name可能已经更新,但也可能没有更新。

我可以轻松group by的三个基本列。

我还需要做的是交叉比较surnameother_name,如果它们匹配,则nameyear列也是如此,将它们分组为最近的姓氏(记录行时由date决定)。

最终的打印结果应如下所示:

+======+===========+======+
| name |  surname  | year |
+======+===========+======+
| John | Bar (Foo) | 2000 |
+------+-----------+------+
| John |    Foo    | 1990 |
+------+-----------+------+

我意识到这对于SQL查询而言是一项相当复杂的任务。因此,如果您有一个在程序(PHP)中完成的更简单的解决方案,我也将不胜感激。

1 个答案:

答案 0 :(得分:0)

嗯。 。 。在有限的情况下,您只需要更改一次姓氏即可做到这一点:

select t.name, t.year, group_concat(distinct t.surname) as surnames
from t left join
     t tother
     on t.surname = tother.other_name and t.name = tother.name and t.year = tother.year
group by t.name, t.year, coalesce(tother.surname, t.surname);

这里是db<>fiddle(它使用Postgres,因为我发现它更容易设置,但除了group_concat()之外,其他都一样)。