mySQL:UPDATE命令中的子SELECT语句

时间:2013-02-20 17:01:11

标签: php mysql select sql-update subquery

我正在尝试更新visitors中的列。我还在更新查询的SET部分使用了子选择语句。

UPDATE
    visitors AS v
SET
    v.IsFirstVisit = (SELECT COUNT(*) FROM visitors AS v2 WHERE ..... LIMIT 1)

但是,mySQL会返回此错误消息

#1093 - You can't specify target table 'v' for update in FROM clause

我不知道为什么我无法访问内部select语句中的'v'对象。我也不想使用多个语句,因为这会导致性能问题。

问题:如何在内部选择中使用“v”对象?

更新: 这是整个查询

UPDATE
    visitors AS v
SET
    IsFirstVisit = (SELECT Count(*) FROM visitors AS v2 WHERE v2.VisitorId < v.VisitorId AND v2.IP = v.IP AND v2.DateTime > v.DateTime [TODO:SUBTRACT30MINUTES] LIMIT 1)
WHERE
    VisitorId = "991"

2 个答案:

答案 0 :(得分:1)

我猜你在找这个

 UPDATE
    visitors 
 SET
    IsFirstVisit = (SELECT COUNT(*) FROM visitors  WHERE ..... LIMIT 1)

编辑:

试试这个

    UPDATE
       visitors
    SET
         IsFirstVisit = (SELECT Count(*) FROM visitors v2 inner join visitors v 
         ON v.VisitorId = v2.VisitorId WHERE v2.IP = v.IP AND v2.DateTime > v.DateTime AND v2.VisitorId < v.VisitorId [TODO:SUBTRACT30MINUTES] LIMIT 1)
    WHERE
    VisitorId = "991"

答案 1 :(得分:1)

inner join声明中的UPDATE不是一个坏主意。

UPDATE
    visitors inner join (SELECT COUNT(*) as test FROM visitors v) as v
 SET
    isfistvisit = v.test;

另一种解决方法,我不是它的忠实粉丝。

update visitors
   set isfistvisit = (
      select count(*) from (
         select count(*) from visitors
      ) as x
      )

Demo