简体   繁体   中英

SELECT FROM two different tables with UNION and ORDER BY one column that both tables have --> Use of index?

I want to SELECT FROM two different tables that both have a column with a timestamp (INT).

The answers to this question ( Select separate rows from two tables, order by date ) are showing me how to use UNION ALL to achieve this but my question is: Can this query be made fast if there are a lot of entries in both tables?

A code example could be:

SELECT id as foo_id, NULL as bar_id, value as foo_value, timestamp as timestamp, NULL as bar_value
FROM foo WHERE x = const.
UNION ALL
SELECT NULL as foo_id, id as bar_id, NULL as foo_value, value as bar_value, timestamp as timestamp
FROM bar WHERE y = const.
ORDER BY timestamp DESC

So I assume that this query can make use of indices for x and y, but can it also make use of the 2 indices for timestamp (1 per table)? I cannot afford that the query is somehow slow and uses filesort or table scans.

You can't use multiple indexes in a simple select

SQL engines use at most one index to read data, because of what an index is . It is just an ordering of your rows. If it uses the index on x, then the data it reads is not in timestamp order, if it uses the index on timestamp, then it isn't in x order.

You can ask MySQL to EXPLAIN what it will do with a query, that will give you a query plan, or you can run the query and see if it is fast enough , and you can try hinting different indexes to test if you pick better. However all those things won't magically make something less complex than it is.

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