简体   繁体   中英

MySQL query takes 2 minutes

I have a problem. I am running a MySQL PhpMyAdmin server and I have 3 tables:

  • CandlestickData
  • CandlestickDataHist1
  • CandlestickDataHist2

Then I created a few with the following source query:

SELECT
    a.*
FROM
    (
    SELECT
        *,
        'CandlestickData' AS SOURCE
    FROM
        CandlestickData
    UNION
SELECT
    *,
    'CandlestickDataHist1' AS SOURCE
FROM
    CandlestickDataHist1
UNION
SELECT
    *,
    'CandlestickDataHist2' AS SOURCE
FROM
    CandlestickDataHist2
) AS a
ORDER BY
    a.MainKey
DESC

This gives me a view with 1.7 million records. When I do the following simple query on the view:

SELECT * FROM my_created_view;

It takes arround 2 minutes to execute the query. Is there a way to make it faster?

You can speed it up a bit using UNION ALL rather than UNION :

SELECT cd.*
FROM ((SELECT cd.*, 'CandlestickData' AS SOURCE
       FROM CandlestickData cd
      ) UNION ALL
      (SELECT cd.*, 'CandlestickDataHist1' AS SOURCE
       FROM CandlestickDataHist1 cd
      ) UNION ALL
      (SELECT cd.*, 'CandlestickDataHist2' AS SOURCE
       FROM CandlestickDataHist2 cd
      )
     ) cd
ORDER BY cd.MainKey DESC;

This will still require sorting all the data. However, it will remove the overhead for removing duplicates. I might venture that it would be about 50% faster.

If you really want to speed the query, you need to store all the data in a single table. Then you can create an index for the order by key.

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