简体   繁体   中英

MySQL Subquery With LIMIT vs JOIN

I would prefer to use a JOIN for this, but none of the solutions are either viable due to performance impacts or they don't return the right result set.

The RunTime column is a UNIX timestamp captured every night at midnight. Not every entry will occur every night, meaning an entry for Entry1 may have occurred two days ago, but not today.

Schema:

 `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Name` varchar(32) NOT NULL,
  `Category` int(11) NOT NULL,
  `RunTime` int(11) NOT NULL,
  UNIQUE KEY `ID` (`ID`),

Example Desired Results:

+-------------+----------------+----------+
| Name        | LastRunTime        | Count    |
+-------------+----------------+----------+
| Random Name |     1339131600 |       73 |
| RandomName2 |     1337131600 |       13 |
... etc

Essentially, my working query looks like the below. It will query the table for yesterdays data.

select Name,
       RunTime AS LastRunTime,
       count(*) AS Count
from TABLE
where RunTime = 
    (
    select DISTINCT( RunTime ) from TABLE WHERE r.Name=Name order by RunTime LIMIT 1,1
    ) 
and Category in 
    (
    select AnotherTable .ID from AnotherTable where AnotherTable.Status = 1
    )

group by Name

The problem is, this query is slow. I want to move away from the first subquery, on the RunTime column, but the LIMIT and association is getting the best of me. The above takes a very, very , long time.

Does anyone have an example of a way to:

Get the second most recent RunTime , the count of rows for the second most recent RunTime , quickly and efficiently where RunTime is not consistent across all rows?

Any suggestions are appreciated!

    Select Name, Max(RunTime ) as  LastRunTime        ,Count(*) as Count
    from TABLE a
    Inner join AnotherTable b ON a.Category =b.ID and   b.Status = 1
    GROUP BY name
    Having LastRunTime < Max(RunTime )

I stuck with a subquery but changed the timeframe to WHERE RunTime = (SELECT MAX(RunTime) - 86400... .

All other solutions or attempts where either too demanding or convoluted.

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