1

I'm trying to update a column in visitors. I'm also using a sub select statement for the SET part of the update query.

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

However, mySQL returns this error message

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

I have no clue why I can't access the 'v' object within the inner select statement. I also don't want to use multiple statements as this would cause a performance issue.

Question: How can I use the 'v' object within the inner select?

Update: This is the entire query

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"
4

2 回答 2

1

i guess you looking for this

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

edit:

try this

    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"
于 2013-02-20T17:03:02.717 回答
1

inner joininUPDATE语句不会是一个坏主意。

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
      )

演示

于 2013-02-20T17:10:35.743 回答