1

I cannot get the code below to work. I'm trying to set a variable from a query and use it twice in another. The query runs fine if I copy the first query into the location of the variables. Since the first query will always return the same result I would prefer to not run it twice.

        SET @sid = (SELECT status_id
                    FROM user_relationship_status
                    WHERE status = 'LIKE');

        INSERT INTO user_relationships (user_id, target_user_id, status_id)
        VALUES (
          17,
          22,
          @sid
        )
        ON DUPLICATE KEY UPDATE
          status_id = VALUES(@sid)

Also user_id and target_user_id are both primary keys.

2
  • In what way does it not work? Are there any error messages? Commented Mar 27, 2016 at 1:38
  • 2
    SELECT @sid:=status_id FROM... Commented Mar 27, 2016 at 1:40

2 Answers 2

1

This is valid syntax in SQL Server, provided sub-query return's only one row.

 SET @sid = (SELECT status_id
                    FROM user_relationship_status
                    WHERE status = 'LIKE');

In Mysql you need to do like this

SELECT @sid:= status_id 
  FROM user_relationship_status
 WHERE status = 'LIKE'

Insert query should be like

I cannot get the code below to work. I'm trying to set a variable from a query and use it twice in another. The query runs fine if I copy the first query into the location of the variables. Since the first query will always return the same result I would prefer to not run it twice.

    SET @sid = (SELECT status_id
                FROM user_relationship_status
                WHERE status = 'LIKE');

    INSERT INTO user_relationships (user_id, target_user_id, status_id)
    VALUES (
      17,
      22,
      @sid
    )
    ON DUPLICATE KEY UPDATE
      status_id = @sid
Sign up to request clarification or add additional context in comments.

2 Comments

I get: INSERT INTO user_relationships (user_id, target_user_id, status_id) VALUES ( 17, 18, @sid ) ON DUPLICATE KEY UPDATE status_id = VALUES(@sid) Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@sid)' at line 8 0.000 sec
@ovg - Updated my answer
0

Use below script to set @sid

SELECT status_id INTO @sid FROM user_relationship_status WHERE status = 'LIKE' limit 1;

2 Comments

This also works for variables but I'm still having trouble with the insert part..
For error code 1452: users table does not any entry for user_id 18.

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.