查询目的:MySQL查询的目的是查找事件(y.indicator = '1'
)与紧接其时间戳的行之间的时间戳差异。这些错误在数据库中多次出现。
样本数据:
row_id | indicator | timestamp
----+---------+--------+----------------------------
abcdef | 0 | 1592900862
abcdef | 0 | 1592900900
abcdef | 1 | 1592900905
abcdef | 1 | 1592900907
qrstuv | 0 | 1592900863
qrstuv | 1 | 1592900867
qrstuv | 0 | 1592900880
qrstuv | 0 | 1592900900
qrstuv | 1 | 1592900905
示例输出
row_id | Diff | timestamp
----+---------+--------+----------------------------
abcdef | 5 | 1592900905
abcdef | 2 | 1592900907
qrstuv | 4 | 1592900867
qrstuv | 5 | 1592900805
数据库:需要UNION
包含16个不同的表。这些表合起来有千万行。
查询工作,当条件AND x.row_id IN ('abcde12242fdsdsfds','safzxvdseafcz')
仅包含一个row_id
时,但是中断,当我添加其他row_id
时(因此将在下面的示例中中断)。我将需要在20,000 row_id
上运行它。
因此将其归结为两个问题:
JOIN
表y
而不重复整个UNION
语句。SELECT x.row_id, x.timestamp,
MIN(x.timestamp - y.timestamp) AS Diff
FROM
(SELECT * FROM table01db.db
UNION SELECT * FROM table02db.db
UNION SELECT * FROM table03db.db
UNION SELECT * FROM table04db.db
UNION SELECT * FROM table05db.db
UNION SELECT * FROM table06db.db
UNION SELECT * FROM table07db.db
UNION SELECT * FROM table08db.db
UNION SELECT * FROM table09db.db
UNION SELECT * FROM table10db.db
UNION SELECT * FROM table11db.db
UNION SELECT * FROM table12db.db
UNION SELECT * FROM table13db.db
UNION SELECT * FROM table14db.db
UNION SELECT * FROM table15db.db
UNION SELECT * FROM table16db.db ) AS x
JOIN (SELECT * FROM table01db.db
UNION SELECT * FROM table02db.db
UNION SELECT * FROM table03db.db
UNION SELECT * FROM table04db.db
UNION SELECT * FROM table05db.db
UNION SELECT * FROM table06db.db
UNION SELECT * FROM table07db.db
UNION SELECT * FROM table08db.db
UNION SELECT * FROM table09db.db
UNION SELECT * FROM table10db.db
UNION SELECT * FROM table11db.db
UNION SELECT * FROM table12db.db
UNION SELECT * FROM table13db.db
UNION SELECT * FROM table14db.db
UNION SELECT * FROM table15db.db
UNION SELECT * FROM table16db.db ) AS y
ON x.row_id = y.row_id
WHERE x.indicator = '1'
AND x.timestamp > y.timestamp
AND x.row_id IN ('abcde12242fdsdsfds','safzxvdseafcz')
GROUP BY x.row_id, x.timestamp