简体   繁体   中英

Is possible to make this SQL query run faster?

Two simple tables

Base table

+--------+
|id|value|
+--------+
|  |     |
+--------+

Event table (with a lot of data..)

+--------------+
|id|event| date|
+--------------+
|  |     |     |
+--------------+

Then I would like to have a list of all base.value with corresponding to their last events (including values without event entries)

+----------------+
|id|lastEvt|value|
+----------------+
|  |       |     |
+----------------+

This is a (working but) very slow attempt

SELECT *
  FROM  ( 
    SELECT base.id,
           event.event,
           base.value
      FROM base
           LEFT OUTER JOIN event
                        ON base.id = event.id
     ORDER BY event.date DESC
) 
AS res
 GROUP BY res.id;

I suspect there is a better/faster way of doing the query, but I don't know how..

SELECT b.id, b.value, e.event
    FROM base b
        LEFT JOIN (SELECT id, MAX(date) AS LastEventDate
                       FROM event
                       GROUP BY id) q
            INNER JOIN event e
                ON q.id = e.id
                    AND q.LastEventDate = e.date
            ON b.id = q.id
SELECT 
b.id, b.value, e.event
FROM Base b 
LEFT JOIN Event e ON (b.id = e.id)
ORDER BY e.date DESC
GROUP BY b.id

I assume you have proper indexes on both of those tables.

Maybe I'm missing something, but it seems as though this should work:

SELECT base.id, 
       base.value, 
       event.date 
FROM 
       base 
       LEFT OUTER JOIN 
           event ON base.id = event.id 
ORDER BY event.date DESC 
GROUP BY base.id

As far as whether or not the query above is faster, I assume it would be because it does not include any subqueries, however you'd have to benchmark to verify.

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