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"

2 Answers 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"
Sign up to request clarification or add additional context in comments.

3 Comments

That would not work since I have to access both visitor objects within the "...." of the WHERE clause.
I added the whole query to the question.
In your new solution, the inner select statement does not interact with the outer one, but I think I can just insert the VisitorId from within PHP there. That'll work. Thank you.
1

The inner join in UPDATE statement won't be a bad idea.

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

Another workaround which Im not a big fan of it.

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

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.