mysql - 带条件插入

标签 mysql

我有这张表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 分钟。如果是这样,则应插入数据)

更新

我现在有这些数据。正如您所看到的,时间字段包含昨天的值,因此应插入任何新数据:

enter image description here

我按照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/

相关文章:

php - 给出警告 : mysql_fetch_assoc() expects parameter 1 to be resource, 对象

javascript - 使用php在mysql中插入多条记录

mysql - 如何在MySql中返回具有相同列值的行

php - MySQL 搜索优化以获得更好的性能

php - 更新和插入多行到 MySQL 数据库

mysql - LOAD DATA LOCAL INFILE 正在产生空值,其中小时为 00

mysql - Eloquent:如何连接一个直接相关的表和一个间接相关的表?

php - CakePHP:基于 IP 地址每天发布一个帖子

php - mysqli_stmt_bind_param 用于搜索

mysql - 在 MySQL 5.0 中创建 MySQL 空间过程