来自存储过程优化的MYSQL查询

时间:2019-03-14 07:40:17

标签: mysql sql

我要优化的表结构如下:

stores
------------
id | address

products
------------------------
id | name | type | price

现在,我有一个创建临时表store_products的存储过程:

store_products
-----------------------------------
id | store_id | product_list | type

以及填充store_products临时表的代码:

INSERT into store_products
    SELECT (
        (100+s.id) AS id,
        s.store_id AS store_id,
        'books' AS type,
        IFNULL(CONCAT(',', CONCAT(GROUP_CONCAT(DISTINCT p.name ORDER BY p.name),',')),'') AS store_products
    FROM
        stores s
    LEFT JOIN products p on p.type = 'books'

INSERT into store_products
    SELECT (
        (200+s.id) AS id,
        s.store_id AS store_id,
        'fruits' AS type,
        IFNULL(CONCAT(',', CONCAT(GROUP_CONCAT(DISTINCT p.name ORDER BY p.name),',')),'') AS store_products
    FROM
        stores s
    LEFT JOIN products p on p.type = 'fruits'

现在我有来自store_products的一些查询,如下所示:

SELECT store_id FROM product_list WHERE FIND_INSET('product', product_list)

由于FIND_INSET()不使用索引,因此会导致性能下降。

我必须解决的一个想法是使用某种多对多表来存储产品与商店的关系。但是我不知道如何在存储过程中创建它。

也许还有更多的想法可以优化这一点?

0 个答案:

没有答案