PHP Oracle query select statement inside loop slow

前端 未结 1 713
清酒与你
清酒与你 2021-01-29 08:55

I have this php function to check and insert data from text file to database.

//Get All Model
$qModel = oci_parse($c1, \"SELECT MODELID, MODEL_NAME FROM MEP_TBL_         


        
相关标签:
1条回答
  • 2021-01-29 09:16

    If I've read your code correctly, what you're after is a single MERGE statement that you can run on the database. I don't know PHP, so I can't give you how it should be called, but I can give you the SQL statement to run:

    MERGE INTO mep_tbl_output_details tgt
      USING (SELECT mtm.modelid,
                    mtm.model_name,
                    mtmc.configurationid,
                    mtmc.date_code,
                    mtmc.read_row_after,
                    mtmc.create_from_format,
                    mtmc.ip_address,
                    mtmc.status,
                    mtmc.ts_code
             FROM   mep_tbl_model mtm
                    INNER JOIN mep_tbl_model_configuration mtmc ON mtm.modelid = mtmc.modelid_fk
             WHERE  mtm.active = 'Y'
             AND    mtm.location = 'PCBA') src
        ON (tgt.modelid_fk = src.modelid
            AND tgt.ts_code = src.ts_code
            AND tgt.configurationid_fk = src.configurationid
            AND tgt.runningdate = :log_date
            AND tgt.shift = 'Morning'
            AND tgt.quantity_status = 'OK')
    WHEN NOT MATCHED THEN
      INSERT (tgt.modelid_fk, tgt.running_date, tgt.quantity_status, tgt.ts_code, tgt.shift, tgt.configuration_fk)
      VALUES (src.modelid, :log_date, 'OK', src.ts_code, 'Morning', src.configurationid);
    

    This does the join you were reinventing with your loops, links it back to the table you're trying to insert into, and only inserts a row if it doesn't already exist in the table.

    You would need to write the PHP code to execute this, having passed the log_date in as a bind variable.

    By binding the variable, you allow the database to skip the hard parse (i.e. finding out the best way to execute the query), which saves time.

    By not fetching data and manually looping round before selecting more data and working out if you need to do the insert, you skip a whole lot of context switching and pulling/pushing data across the network. Let the database do the heavy lifting; it's what it's designed to do!

    0 讨论(0)
提交回复
热议问题