组合来自同一组数据的两个基于时间的查询

时间:2013-12-10 20:12:50

标签: mysql timezone

我有一个数据库,其中包含两个时区内多个站点的事件,并且都报告了当地时间。我需要获取最近12小时的数据并将其放入CSV格式。我输入了一个联合,当它输出没有ORDER BY的数据时,我在使用INTO OUTFILE部分运行它时会出现别名错误。我错过了什么?

(SELECT
    comp.locationid,
    comp.name,
    event.status,
    event.starttime,
    event.endtime
FROM
    comp,event
WHERE
    event.endtime >= DATE_SUB(NOW(), INTERVAL 12 HOUR)
    AND event.endtime < NOW()
    AND event.compid = comp.id
    AND comp.timezone = "EST")


UNION


(SELECT
    comp.locationid,
    comp.name,
    event.status,
    event.starttime,
    event.endtime
FROM
    comp,event
WHERE
    event.endtime >= DATE_SUB(NOW(), INTERVAL 15 HOUR)
    AND event.endtime < DATE_SUB(NOW(), INTERVAL 3 HOUR)
    AND event.compid = comp.id
    AND comp.timezone = "PST")


ORDER BY comp.locationid
INTO OUTFILE
    "report.csv"
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
;

2 个答案:

答案 0 :(得分:0)

为表格提供别名会有所帮助

(SELECT
    comp.locationid,
    comp.name,
    event.status,
    event.starttime,
    event.endtime
FROM
    comp,event
WHERE
    event.endtime >= DATE_SUB(NOW(), INTERVAL 12 HOUR)
    AND event.endtime < NOW()
    AND event.compid = comp.id
    AND comp.timezone = "EST") AS T


UNION ALL


(SELECT
    comp.locationid,
    comp.name,
    event.status,
    event.starttime,
    event.endtime
FROM
    comp,event
WHERE
    event.endtime >= DATE_SUB(NOW(), INTERVAL 15 HOUR)
    AND event.endtime < DATE_SUB(NOW(), INTERVAL 3 HOUR)
    AND event.compid = comp.id
    AND comp.timezone = "PST") AS T2
ORDER BY comp.locationid
INTO OUTFILE
    "report.csv"
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
;

答案 1 :(得分:0)

<强>更新:

  1. 您无法在ORDER BY的{​​{1}}子句中引用特定的表名。据说只是改变

    UNION

    简单地

    ORDER BY comp.locationid
             ^^^^^
    
  2. 此外,您似乎最有可能使用ORDER BY locationid 代替UNION ALL。所以也要改变它,因为UNION需要额外的处理步骤来消除重复。

  3. 删除UNION

  4. SELECT周围的括号
  5. 将所有双引号更改为单引号