简体   繁体   中英

MySQL left outer join the same table multiple times?

So I have a MySQL dilemma which seemed to be relatively simple, however not the case.

I have two tables: one which holds a list of unique ids to display and another table which lists the ids next to a timestamp.

======   ============================
| ID |   | ID |      Timestamp      |
======   ============================
| 1  |   | 1  | 2015-10-10 00:00:00 |
| 2  |   | 1  | 2015-10-10 00:10:00 |
| .. |   | 2  | 2015-10-10 00:00:00 |
======   ============================

I need to display a boolean if the relevant id has records in Table B between two Date-Times and the last date it was active of all time .


视觉图


I have tried something similar to this:

SELECT 
    a.`ID`, 
    MAX(b1.`Timestamp`) IS NOT NULL as 'Active',
    MAX(b2.`Timestamp`) AS 'LastActive'
FROM `Table-A` a
LEFT OUTER JOIN `Table-B` b1
    ON a.ID = b1.ID
    AND b1.`Timestamp` BETWEEN @startTime AND @endTime
LEFT OUTER JOIN `Table-B` b2
    ON a.ID = b2.ID
GROUP BY a.ID
;

Currently not sure why: but the query seems to run infinitely and not get any results. Can anyone suggest the correct way to get the results needed in my query?


EDIT:

Here is an EXPLAIN SELECT for the above query.

解释选择

Use this

SELECT 
    a.*, 
    IF(b1.cnt IS NULL, FALSE, TRUE) AS is_found, 
    IFNULL(b2.dt, '-') AS max_dt 
FROM table1 a 
    LEFT OUTER JOIN (
        SELECT 
            id, 
            COUNT(*) AS cnt 
        FROM table2 
        WHERE 
            `timestamp` BETWEEN '2015-01-01' AND '2015-12-31' 
        GROUP BY 1) b1 
    ON a.id=b1.id 
    LEFT OUTER JOIN (
        SELECT id, 
            MAX(TIMESTAMP) AS dt 
        FROM table2 
        GROUP BY 1) b2 
    ON a.id=b2.id

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