我有这张表pageview
id | visitor | id_realestate | time
-----------------------------------------------
我希望插入记录,只要最后一个 time
对于该特定的 id_realestate
至少已经有 30 分钟了已由该特定visitor
检查过
更新
让事情变得更清楚。如果我已准备好将这些数据插入表中
visitor:"axax"
id_realestate:120
time:NOW()
如果只有最后一条记录具有这些值,则应插入这些值 visitor:"axax"
& id_realestate:120
超过 30 分钟(通过检查字段 time
中我提到的两个值的最后一条记录,并将其与 NOW()
进行比较,如果差异大于 30 分钟。如果是这样,则应插入数据)
更新
我现在有这些数据。正如您所看到的,时间字段包含昨天的值,因此应插入任何新数据:
我按照anubhava的建议使用了此查询,但什么也没发生(没有添加新记录/没有错误)
$query='insert into pageview
select "q17872745t", 150, now()
from pageview a
where id_realestate=150 and DATE_ADD(now(),INTERVAL -30 MINUTE) > (
select max(time) from pageview b where a.id_realestate=b.id_realestate AND a.visitor=b.visitor
)';
更新
我将查询修改为以下内容,它正在工作但是 它与每个 time
进行比较如果最近时间是 30 分钟,则相应地插入一条记录(意味着将记录加倍)。所以如果我有两条具有相同 visitor
的记录和id_realestate
它将与这两条记录进行比较,如果 time
两者都是 30 分钟前,那么它会插入 2 条相同的记录,而它应该插入一条记录。
$query='insert into pageview (visitor,id_realestate,time)
select "q17872745t", 150, now()
from pageview a
where id_realestate=150 and DATE_ADD(now(),INTERVAL -30 MINUTE) > (
select max(time) from pageview b where a.id_realestate=b.id_realestate AND a.visitor=b.visitor
)';
更新:[已解决]
我添加了LIMIT 1
在上述查询结束时,现在它可以正常工作了。这是最终的查询:
$query='insert into pageview (visitor,id_realestate,time)
select "q17872745t", 150, now()
from pageview a
where id_realestate=150 and DATE_ADD(now(),INTERVAL -30 MINUTE) > (
select max(time) from pageview b where a.id_realestate=b.id_realestate AND a.visitor=b.visitor
) LIMIT 1';
最佳答案
不是一个非常明确的问题,但您可以使用如下查询:(未经测试)
insert into pageview
select 15, 'A VISITOR', 10, now()
from pageview a
where id_realestate=10 and DATE_ADD(now(),INTERVAL -30 MINUTE) > (
select max(news_release) from pageview b where a.id_realestate=b.id_realestate
);
关于mysql - 带条件插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9251082/