5

Please see sample code

-- 1st select, getting AssetID from asset table
SELECT GROUP_CONCAT(AssetID)
INTO @AssetIDs
FROM  asset;

-- 2nd select, use @AssetIDs in an IN clause 
SELECT AssetID
from asset
where AssetID IN (@AssetIDs)

From the 1st select, it returns 10 IDs and those IDs get stored in @AssetIDs So i would imagine @AssetIDs = '1,2,3,4,5,6,7,8,9,10'

However, the second select always return the first ID, 1.

Can anyone help me find a way to select the list of IDs in a variable that reuse that variable in the IN clause?

5
  • 3
    Why use a variable at all? just in (select AssetID from asset) - If you reall have to do it see stackoverflow.com/questions/21101211/mysql-variable-in-clause Commented Oct 4, 2016 at 14:57
  • 1
    @AlexK. and then it all just comes down to select AssetID from asset as the simplest query anyway with no IN Commented Oct 4, 2016 at 21:00
  • @drew ha yes good point Commented Oct 5, 2016 at 18:17
  • 3
    In order to evaluate where AssetID IN ('1,2,3,4,5,6,7,8,9,10'), MySQL implicitely converts your string '1,2,3,4,5,6,7,8,9,10' to int which it does by simply taking all digits from left, which is '1' only. So the query finds the record with ID 1. I don't like this conversion very much, I'd rather see it resulting in an error, because '1,2,3,4,5,6,7,8,9,10' obviously isn't an integer. But well, this is how the MySQL guys decided to do it. Commented Oct 5, 2016 at 20:21
  • @ThorstenKettner ahh i see it now. That's why it's always returning the first ID Commented Oct 5, 2016 at 20:24

2 Answers 2

6

I used a tmp table instead.

DROP TEMPORARY TABLE IF EXISTS tmpassetlist; 
CREATE TEMPORARY TABLE tmpassetlist AS
(
    SELECT AssetID
    FROM asset
    WHERE (condition)
);

Then do a join:

SELECT AssetID
from asset JOIN tmpassetlist
ON asset.AssetID = tmpassetlist.AssetID

I think it's also better performance wise because IN clause could get very slow when the list gets longer.

Sign up to request clarification or add additional context in comments.

Comments

1

I also wanted to find some ids then use them in IN clause in my procedure:

-- first find some ids
SELECT GROUP_CONCAT(AssetID)
INTO @AssetIDs
FROM  asset;

-- compose string query using found ids and execute
SET @query = CONCAT(
    "SELECT *
    FROM asset
    WHERE AssetID IN (",
    @AssetIDs,
    ")"
);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

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.