首页 文章

SQL(PHP)与group by和cross列比较

提问于
浏览
1

我有一个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 |
+------+---------+------------+------+------+

我正在尝试将记录分组给同一个人 . Same person is identified by name, surname and year 出生 .

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

我可以轻松 group by 这三个基本栏目 .

我需要做的是 cross compare the surname and other_name and if they match and so do the name and year columns, group them under the most recent surname (在记录行时由 date 决定) .

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

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

我意识到这对SQL查询来说是一项复杂的任务 . 因此,如果您在程序(PHP)中完成了更简单的解决方案,我也会很感激 .

1 回答

  • 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() 之外都是一样的) .

相关问题