简体   繁体   English

使用DB2查询加入mysql数据进行插入

[英]Using DB2 query to join into mysql data for insert

I'm trying to get a script together in php that takes a query from DB2, using sql, and then uses that result set by equating it to data in a mysql table in anther connection and inserts results based on that into another.我正在尝试在 php 中组合一个脚本,该脚本使用 sql 从 DB2 获取查询,然后通过将其等同于花药连接中的 mysql 表中的数据来使用该结果集,并将基于该结果的结果插入到另一个中。

Basically, My db2 query returns several fields that are needed to determine the ID of a table in My SQL基本上,我的 db2 查询返回几个字段,这些字段用于确定 My SQL 中的表的 ID

Below I have an example:下面我举个例子:

I'm selecting from here: DB2 Query Results我从这里选择:DB2 查询结果

Dealer | Style | Frame | Cover | Color | Placements | shipdate
---------------------------------------------------------------
123        1      1234    12       1         2         20180219
123        2      1235    12       1         2         20180219
123        3      1236    12       1         2         20180219

I need to join the former data, in a sense, to the following data in the SKU Table (db2.style = sku.groupID, db2.frame = sku.frame, db2.cover = sku.cover, and db2.color = sku.color) in order to get the correct ID在某种意义上,我需要将之前的数据加入到 SKU 表中的以下数据中(db2.style = sku.groupID、db2.frame = sku.frame、db2.cover = sku.cover 和 db2.color = sku.color) 以获得正确的 ID

ID | Frame | GroupID | cover | color 
------------------------------------
15    1234      1        12      1
16    1235      2        12      1
17    1236      3        12      1

Then below, I need to do an insert of the previously determined ID, as well as some of the data from the original DB2 query (insert style into groupID, dealer into dealerID, shipdate into startdate, placements into placements)然后在下面,我需要插入先前确定的 ID,以及来自原始 DB2 查询的一些数据(将样式插入 groupID,dealer 插入dealerID,shipdate 插入 startdate,placement 插入 Places)

INSERT would result in: (skuplacement table) INSERT 将导致:(skuplacement 表)

sku_id | groupID | dealerID | startDate | expirationDate          | placements
------------------------------------------------------------------------------
15          1       123        20180226    (shipdate + 127 days)       2
16          2       123        20180226    (shipdate + 127 days)       2
17          3       123        20180226    (shipdate + 127 days)       2

I hope this makes sense.我希望这是有道理的。

I've included my full script as of right now, but My INSERT/SELECT/JOIN for MYSQL is missing.我现在已经包含了我的完整脚本,但是我的 MYSQL 的 INSERT/SELECT/JOIN 丢失了。 I'm not sure how to go about this right now, but I have both connections working.我现在不确定如何解决这个问题,但我的两个连接都在工作。 It's just a matter of creating the correct query.这只是创建正确查询的问题。

I'm happy to answer any questions to clear up confusion.我很乐意回答任何问题以消除困惑。

            <?php


            //Establilsh MySql Connection
            $mysqlConn = new mysqli($mysqlServer, $mysqlUser, $mysqlPass);

            //Check MySQL connection
            if($mysqlConn->connect_error){
              die("Connection Failed: " .$mysqlConn->connect_error);
            }
            echo "Connected Succssfully to Mysql";

            //Establish DB2 connection
            $DB2Conn = odbc_connect();

            //Check DB2 Connection
            if(!$DB2Conn){
              die("Could not connect");
            }else{
                echo"Connected to DB2";
            }



            $plcQueryDB2 = "

                   select
                        xcstno as dealer,
                        p.style as Style,
                        trim(p.framfmt) as Frame,
                        p.cover1 as Cover,
                        p.color1 as Color,
                        sum(skunoc) as placements,
                        p.extd1d as shipdate
                    from pieces p
                    where left(shipdate, 4) >= '2016'
                    group by xcstno, xslsno, sup, f.style, f.grpnam, f.framfmt, f.cover1, f.color1, f.coldss,a.extd1d
                    order by left(shipdate, 4) ASC, REP
                ";

            $prep = odbc_prepare($DB2Conn, $plcQueryDB2);
            $exec = odbc_execute($prep);

            $result = odbc_exec($DB2Conn, $plcQueryDB2);

            if(!$prep){
                die("Could Not Run Query");
            }else{
                echo "DB2 Query Successful";
            }


            while(odbc_fetch_row($result)){
                     for($i=1;$i<=odbc_num_fields($result);$i++){
                    echo "Result is ".odbc_result($result,$i);
                }
            }


            /*Need to get an INSERT created here*/

            $InsertSKUS = "

                    INSERT INTO skuPlacement
                    values (?,?,?,?,?,?)     
            ";

            /* This is my problem. I need to select from another table called skus and insert into skuPlacement based on equating fields from my previous DB2 query and the skus table*/


            ////*CLOSE CONNECTIONS*////


            if (mysqli_close($mysqlConn)){
                echo "MySQL Closed";
            }

            //$CloseDB2 =  odbc_close( $DB2Conn);

            if(odbc_close( $DB2Conn)){
                echo "DB2 Closed";
            }





            ?>

Consider saving your DB2 query results to csv file.考虑将 DB2 查询结果保存到 csv 文件。 Then import the csv file into MySQL with LOAD DATA INFILE (a fast bulk facility) and run needed join append query all inside MySQL:然后使用LOAD DATA INFILE (一种快速批量工具)将 csv 文件导入 MySQL,并在 MySQL 中运行需要的 join append 查询:

DB2 Query CSV DB2查询 CSV

try {
    $DB2Conn = odbc_connect();

    $plcQueryDB2 = "...";
    $prep = odbc_prepare($DB2Conn, $plcQueryDB2);
    $exec = odbc_execute($prep);
    $result = odbc_exec($DB2Conn, $plcQueryDB2);
}
catch(Exception $e) {  
    echo $e->getMessage();  
} 

// Writing column headers
$columns = array('Dealer', 'Style', 'Frame', 'Cover', 'Color', 'Placements', 'shipdate');
$fs = fopen('DB2_Query.csv', 'w');
fputcsv($fs, $columns);      
fclose($fs);

// Writing data rows
while($arr = odbc_fetch_array($result)) {
    $fs = fopen('DB2_Query.csv', 'a');
      fputcsv($fs, $arr);
    fclose($fs);
}

odbc_close($DB2Conn);
$DB2Conn = null;

MySQL Queries (run separately in PHP or console) MySQL查询(在 PHP 或控制台中单独运行)

$mysqlConn->query("CREATE TABLE IF NOT EXISTS db2Temp (
                       dealer INTEGER,
                       style INTEGER,
                       frame INTEGER,
                       cover INTEGER,
                       color INTEGER,
                       placements INTEGER,
                       shipdate DATE
                  )");

$mysqlConn->query("DELETE FROM db2Temp");

$mysqlConn->query("LOAD DATA LOCAL INFILE /path/to/DB2Query.csv
                   INTO TABLE db2temp
                   FIELDS TERMINATED BY ','
                   OPTIONALLY ENCLOSED BY '\"'
                   LINES TERMINATED BY '\n'
                   IGNORE 1 LINES");

$mysqlConn->query("INSERT INTO skuPlacement (sku_id, groupID, dealerID, startDate,
                                             expirationDate, placements)
                   SELECT sku.ID, sku.Group_ID, db2.dealer, db2.shipDate,
                          DATE_ADD(
                               DATE_FORMAT(CONVERT(db2.shipDate, CHAR(8)), '%Y-%m-%d'), 
                               INTERVAL 127 DAY) as expirationDate,
                          db2.placements
                   FROM sku
                   INNER JOIN db2temp db2
                   ON db2.style = sku.groupID
                   AND db2.frame = sku.frame
                   AND db2.cover = sku.cover
                   AND db2.color = sku.color
                   WHERE NOT EXISTS                  
                      (SELECT 1 FROM skuPlacement p
                       WHERE sku.ID = p.sku_ID)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM