【问题标题】:Merge MySQl rows as result where data is the newest将 MySQl 行合并为数据最新的结果
【发布时间】:2016-12-03 01:44:39
【问题描述】:

我有一个问题,我的数据库中有多行包含相同的电子邮件。重复的行是由于联系人希望更新他们的信息,而不是更新,而是作为新行插入。

我想做的是合并给定电子邮件的所有重复行,并将数据合并在一起作为 PHP 中返回的结果。

有一个具体的:

  • 对于 x 行,从给定列合并的值应该是具有最高 id 的行,其中该列不为空。

例如,如果我有这些行:

id      email         prefix       first_name
1       bob@bob.com   Mr.          Bob
2       bob@bob.com                Bob
3       bob@bob.com                Bobby
4       bob@bob.com   Mr           Bobby
5       bob@bob.com                Bob

我希望合并的行变成:

email         prefix       first_name
bob@bob.com   Mr           Bob

由于前缀列不为空的id最高的行是id = 4,因此选择该行中前缀的值合并到最终结果中。

同样,联系人将他的名字从 Bob 更改为 Bobby,然后又改回 Bob。因为最高的id 行包含Bob,这是合并的值。

注意还有更多列,这些只是一个简短的示例。

这是我的 SQL 语句:

$this->db->select('company, title, address_line1, address_line2, address_line3, city, state/prov, country, postal_code');
$this->db->from('visitor_contacts');
$this->db->where('email', $email);

如果有人可以帮助我完成这项工作,将不胜感激。如果这在 SQL 中是可能的,那就太棒了,但如果不是,也可以使用 PHP 解决方案。

【问题讨论】:

    标签: php mysql sql codeigniter merge


    【解决方案1】:

    在 MySQL 中,一种方法使用group_concat()

    select email
           substring_index(group_concat(prefix order by (prefix is not null) desc, id desc separator '|'
                                       ), '|', 1) as prefix,
           substring_index(group_concat(first_name order by (first_name is not null) desc, id desc separator '|'
                                       ), '|', 1) as first_name,
           . . .
    from t
    group by email;
    

    方法是将值连接在一起,然后提取第一个元素。

    一些注意事项:

    • group_concat() 的中间字符串有一个(可配置的)最大长度。您可能需要增加其大小。
    • 所有数据都转换为字符串,但您可以转换回适当的数据类型。
    • 分隔符(本例中为'|')不应出现在任何值中。

    另一种方法使用相关子查询:

    select e.email,
           (select t2.prefix
            from t t2
            where t2.email = t.email and t2.prefix is not null
            order by id desc
            limit 1
           ) as prefix,
           (select t2.first_name
            from t t2
            where t2.email = t.email and t2.first_name is not null
            order by id desc
            limit 1
           ) as first_name,
           . . . 
    from (select distinct email from t) e;
    

    这种方法的优点是保留了原始类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 2012-12-16
      • 1970-01-01
      • 2010-11-12
      相关资源
      最近更新 更多