所以我有一个 MySQL 困境似乎相对简单,但事实并非如此。
我有两个表:一个包含要显示的唯一ID列表,另一个表列出时间戳旁边的ID。
====== ============================
| 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 |
====== ============================
我需要显示一个布尔值,如果相关的id在两个日期时间之间的表B 中有记录,并且它的所有时间的最后一个日期
我尝试过类似的东西:
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
;
目前还不确定原因:但查询似乎无限运行而且没有得到任何结果。任何人都可以建议在我的查询中获得所需结果的正确方法吗?
以上查询的EXPLAIN SELECT
。
答案 0 :(得分:2)
使用此
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