mysql 向mongo迁移备忘

由于之前涉及mysql分表,把用户所关联的各种数据,我们暂设定为abcd,代表四种业务

比如userid 为1 ,可能属于 a1表,a2表,b3表,d4表。
现在要统一改为mongo
实现在user表中有一个abcd字段,类型是数组,分别存储相当应的表明

比如 abcd [0=>a1,1=>b2,2=>c3]这样。

思路也很简单,分表找到数据库属于abcd的所有表,联合查询,取到表名和pid(person id),然后插入更新到mongo abcd字段即可。

以下是简单实现:

<?php
        $conn = mysql_connect("14.11.1.1", "d", "d2015");
        mysql_select_db("dmp", $conn);//选择MYSQL数据库
        mysql_query("set names utf8");//
        $result = mysql_query("SHOW TABLES");
        while ($row = mysql_fetch_array($result)) {
            if (strstr($row[0], 'd_user_aaa_')) {
                //$sql['aaa'][] = $row[0];
                $aaa_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";
            } elseif (strstr($row[0], 'd_user_ccc_')) {
                $ccc_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";
            } else if (strstr($row[0], 'd_user_ddd_')) {
                $ddd_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";
            } else if (strstr($row[0], 'd_user_ttt_')) {
                $ttt_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";
            }
        }
        $aaa_sql = rtrim($aaa_sql, "union all");
        $ccc_sql = rtrim($ccc_sql, "union all");
        $ddd_sql = rtrim($ddd_sql, "union all");
        $ttt_sql = rtrim($ttt_sql, "union all");
        // 可以统计下数据量大小
        //echo "select count(*) from "."($ccc_sql)"." as nums";
        // 测试 先来100条,一般这种情况在cli执行或者放在cron中执行,数据量大不适合在浏览器中跑,会超时。
        //$aaa_sql .= " limit 100";
        $ccc_sql .= " limit 100";
        $res = mysql_query($ccc_sql);
        $conn=new Mongo("mongodb://192.168.1.40:10001/test");
        $collection=$conn->test->d_user;
        while ($row = mysql_fetch_assoc($res)) {
            $collection->update(array("pid"=>(int)$row['pid']),array('$addToSet'=>array('acdt'=>$row['tbname'])));
        }

ps:myslq Union要进行重复值扫描,所以效率比较低。如果合并没有刻意要删除重复行,那么就使用Union All两个要联合的SQL语句 字段个数必须一样,而且字段类型要(一致)因为这些表里就是存了一个pid和时间,mongo的addtoset去重我猜又比mysql快,所以用了union all;

    原文作者:牙小木木
    原文地址: https://segmentfault.com/a/1190000003953877
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞