Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIND_IN_SET slow, can't use IN()

Tags:

mysql

I have a stored procedure and it's running slow. Is there a better way to pass the table id's to the procedure rather that use FIND_IN_SET?

The table column e.fk_trans_history_id is an INT(32)

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `1_trans_hist_ent_items_sel`(b INT,tid TEXT)
BEGIN
SELECT 
    e.id,
    e.fk_trans_history_id,
    e.fk_prod_pack_id,
    e.line_num,
    e.vat_code,
    e.code,
    e.make,
    e.model,
    e.price,
    e.discount,
    e.cover,
    e.warranty,
    p.make,
    p.model,
    p.weight,
    p.width,
    p.depth,
    p.height,
    p.cost,
    p.cover_value_each,
    p.web_model,
    k.stock - k.repair
FROM
    1_trans_history_entries e
        LEFT JOIN
    1_products p ON p.id = e.fk_prod_pack_id
        AND LEFT(code, 1) <> 'P'
        LEFT JOIN
    1_stock k ON k.fk_products_id = p.id AND k.branch = b
WHERE
    (e.code IN ('MiscShip' , 'Collect')
        OR (ASCII(e.code) > 47
        AND ASCII(e.code) < 58))
        AND FIND_IN_SET(e.fk_trans_history_id, tid)
ORDER BY e.id;
END
like image 312
Stephen Bouffe Avatar asked Oct 22 '25 23:10

Stephen Bouffe


1 Answers

Put the IDs you want to match into a temporary table, and join with that table.

CREATE TEMPORARY TABLE temp_trans_hist_ent_items_sel_ids (
    id
);
INSERT INTO temp_trans_hist_ent_items_sel_ids VALUES (1), (10), ...;

Then the query in the procedure can use:

JOIN temp_trans_hist_ent_items_sel_ids AS temp ON e.fk_trans_history_id = temp.id
like image 157
Barmar Avatar answered Oct 24 '25 12:10

Barmar