我的数据库postgresql ver上发生了一场小小的灾难。 8.4。 请帮帮我!
我必须在我的网页上关注我的访问者,如:
表历史记录
whereseenlast varchar(50) uniqid varchar(13) primary key whenseenlast timestamp bla1 varchar(10) bla2 varchar(10) bla3 varchar(10)
示例:
where1.html, **1**, 2000-01-01 00:00:00, somebla1, somebla2, somebla3 where2.html, **1**, 2005-05-05 05:06:07, somebla1, somebla2, somebla3 ... where12345.html, **1**, 2012-11-22 11:22:33, somebla1, somebla2, somebla3
表访问者(uniqid是主键,每个访问者只能在此表中找到一次)
wherseenfirst varchar(50) whereseenlast varchar(50) whenseenfirst timestamp whenseenlast timestamp uniqid varchar(13) PRIMARY KEY notes varchar (20) xyz varchar(20)
示例:
where1.html, where12345.html, 2000-01-01 00:00:00, 2012-11-22 11:22:33, 1, somenote, somexyz
我不小心删除了TABLE访客,但我没有备份。但是,我确信专家很容易通过查询从TABLE历史记录重建TABLE访问者。
(我知道我无法从TABLE 历史记录恢复注释和 xyz COLUMNS,但这不是什么大不了的事)
你能建议解决方案吗?
答案 0 :(得分:0)
这是数据库类的归属分配吗?
首先,您必须为每位访问者选择历史记录中最新和最早的行:
select uniqid, max(whenseenlast) from history group by uniqid
和
select uniqid, min(whenseenlast) from history group by uniqid
然后选择与历史记录表匹配的记录,如下所示:
select frst.uniqid, whenseenfirst, whereseenfirst, whenseenlast, whereseenlast
from
(select h.uniqid, mn.mnseen as whenseenfirst, h.whereseenlast as whereseenfirst
from history h
join (select uniqid, min(whenseenlast) as mnseen from history group by uniqid) mn
on mn.mnseen = h.whenseenlast and mn.uniqid = h.uniqid) frst,
(select h.uniqid, mx.mxseen as whenseenlast, h.whereseenlast as whereseenlast
from history h
join (select uniqid, max(whenseenlast) as mxseen from history group by uniqid) mx
on mx.mxseen = h.whenseenlast and mx.uniqid = h.uniqid) lst
where frst.uniqid = lst.uniqid
您可以在SQLFiddle
上进行验证答案 1 :(得分:0)
尝试:
SELECT DISTINCT ON (uniqid) *
FROM history
ORDER BY uniqid, whenseenlast DESC
它将为您提供每个用户的最新历史记录(每DISTINCT uniqid
个)。
SELECT DISTINCT ON (uniqid) *
FROM history
ORDER BY uniqid, whenseenlast
获取第一条历史记录。
INSERT INTO visitors (uniqid, whereseenlast, whenseenlast, whenseenfirst, whenseenlast ...)
SELECT seen_last.uniqid, seen_last.whereseenlast, seen_last.whenseenlast, seen_first.whereseenlast, seen_first.whenseenlast ...
FROM
(SELECT DISTINCT ON (uniqid) *
FROM history
ORDER BY uniqid, whenseenlast DESC) seen_last
JOIN
(SELECT DISTINCT ON (uniqid) *
FROM history
ORDER BY uniqid, whenseenlast) seen_first
ON seen_last.uniqid = seen_first.uniqid
它会重建你的桌子。
详细信息:DISTINCT ON
答案 2 :(得分:0)
选择 h1.uniqid, h1.whereseenlast asseenfirst, h1.whenseenlast asseefirst, h3.whereseenlast, h3.whenseenlast 来自历史h1 离开加入历史h2 在h1.uniqid = h2.uniqid 和h1.whenseenlast< h2.whenseenlast
加入历史记录h3 在h1.uniqid = h3.uniqid 离开加入历史h4 在h3.uniqid = h4.uniqid 和h3.whenseenlast> h4.whenseenlast
,其中 h2.uniqid为null 和h4.uniqid为空