我有两个查询,它们是与PHP脚本分开运行的。第一个是检查标识符(组(在表中是否有时间戳。
SELECT
group, MAX(timestamp) AS timestamp, value
FROM table_schema.sample_table
GROUP BY group, value
如果没有时间戳,那么它运行第二个查询,从一个单独的表中检索最小时间戳:
SELECT
group, MIN(timestamp) as timestamp, value AS value
FROM table_schema.src_table
GROUP BY group, value
然后继续。
为了简洁起见,我想做的是让一个查询运行第一条语句,但如果为NULL,则默认为第二条语句。我尝试过使用coalize((和CASE语句,但它们要求子查询返回单列(我还没有遇到这个问题(。然后我决定在带有聚合时间戳的表上尝试JOIN,以获得整行,但很快我意识到我不能改变要连接的表(据我所知(。我选择尝试加入两个结果并获得最大值,类似于这样:
编辑:我太累了,这应该是一个UNION,而不是JOIN
抱歉造成任何可能的混淆:(
SELECT smpl.group, smpl.value, MAX(smpl.timestamp) AS timestamp
FROM table_schema.sample_table as smpl
INNER JOIN
(SELECT src.group, src.value, MIN(src.timestamp) AS timestamp
FROM source_table src
GROUP BY src.group, src.value) AS history
ON
smpl.group = history.group
GROUP BY smpl.group, smpl.value
我没有SELECT MAX()
,因为它确实很慢,很可能是因为我的SQL有点生疏。
如果有人知道更好的方法,我将不胜感激!
请尝试以下操作:
select mx.group,(case when mx.timestamp is null then mn.timestamp else mx.timestamp end)timestamp,
(case when mx.timestamp is null then mn.value else mx.value end)value
(
SELECT
group, MAX(timestamp) AS timestamp, value
FROM table_schema.sample_table
GROUP BY group, value
)mx
left join
(
SELECT
group, MIN(timestamp) as timestamp, value AS value
FROM table_schema.src_table
GROUP BY group, value
)mn
on mx.group = mn.group