简体   繁体   中英

How to add index to table view MySQL

I have a problem with database performance because there are too many joins in the query that was built. I have the initiative to create a table view so that the process becomes faster than before, the code is as below

CREATE VIEW dashboard_sales AS (
    SELECT o.order_id,
           o.order_date,
           o.order_status,
           o.order_gender,
           o.order_birth_date,
           op.op_status,
           op.op_payment_code,
           oi.oi_qty,
           op.op_total,
           oi.item_id,
           i.item_name,
           dc.dc_id,
           dc.dc_name,
           dc.dc_sales,
           c.id_city,
           c.name_city,
           pc.pc_caption
    FROM `order` o 
    LEFT JOIN order_items oi
    ON o.order_id = oi.order_id
    LEFT JOIN order_payment op
    ON o.order_id = op.order_id
    LEFT JOIN item i
    ON oi.item_id = i.item_id
    LEFT JOIN distribution_channel dc
    ON o.dc_id = dc.dc_id
    LEFT JOIN city c
    ON o.order_city = c.id_city
    LEFT JOIN payment_channel pc
    ON op.op_payment_code = pc.pc_code
);

but because there are many records and I am looking for a solution that is by adding indexing as below,

CREATE INDEX MyIndex
ON dashboard_sales(op_total, order_date)

but i get some error like this,

#1347 - 'matoa_admin.dashboard_sales' is not BASE TABLE

how to solved this problem? and can it make indexing in the table view?

You need to create index on table(s) not on to the view itself.

op_total and order_date is not the first concern here. You first need to makesure that on clauses on the main query is using indexed columns and if not you may need to create proper indexes for it.

I suggest you to use Explain plan in order to detect performance issues. And then you can have necessary actions.

The query by itself does not give us information and Explain plan is necessary for determining possible problems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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