A. Vreeswijk
A. Vreeswijk

Reputation: 954

MySQL query takes 2 minutes

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

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?

Upvotes: 1

Views: 291

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

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.

Upvotes: 2

Related Questions