如下SQL语句在MySQL中执行需要2秒左右的时间,如果使用UNION ALL进行不去重合并只需要0.4秒,UNION ALL配合DISTINCT来去重速度又变成2秒了,请问如何进行优化?
SELECT
a. KEY,
a. DATA,
a.date_added
FROM
(
(
SELECT
CONCAT('customer_', ca. KEY) AS `key`,
ca. DATA,
ca.date_added
FROM
`cf_customer_activity` ca
)
UNION
(
SELECT
CONCAT('affiliate_', aa. KEY) AS `key`,
aa. DATA,
aa.date_added
FROM
`cf_affiliate_activity` aa
)
) a
ORDER BY
a.date_added DESC
LIMIT 0,
5;
See if the key prefixes of the statements you write are different, there will never be duplication. Just union all
Of course, use QEP first
As for the specific meaning of each field, check the information yourself.
@prolifes is right. Maybe the questioner didn't express it clearly.
I will add another idea, because you only need 5 pieces of data in the end, take 5 pieces from ca, and then take 5 pieces from aa, for a total of 10 pieces of data to sort, this will be very fast.