I have a create that have sub query. To show as example, here is a query that has similarity with my own. Personally I have more table and more arguments on table (The subquery have left join for example). I simplified it for the question.
SELECT
Content,
CASE
WHEN S.User IN (SELECT UserId FROM Users WHERE Deleted = false) AND S.Permission Like '%ADMIN%' THEN 'Admin'
ELSE 'Basic'
END AS UserType,
CASE
WHEN S.User IN (SELECT UserId FROM Users WHERE Deleted = false) THEN 'Here'
ELSE 'Not'
END AS Exist
FROM (
SELECT *
FROM MyTable
WHERE Deleted = false
) as S;
I want to put the SELECT UserId FROM Users WHERE Deleted = false
query into the main table as I'm using the result multiple times. In the example, I'm using the content 2 times. It's only for optimization. Hope it can really help performances.
I tried something like that:
SELECT
Content,
CASE
WHEN S.User IN (AvailableUsers) THEN 'Here'
ELSE 'Not'
END AS Exist,
CASE
WHEN S.User IN (AvailableUsers) AND S.Permission Like '%ADMIN%' THEN 'Admin'
ELSE 'Basic'
END AS UserType
FROM (
SELECT *, (SELECT UserId FROM Users WHERE Deleted = false) as AvailableUsers
FROM MyTable
WHERE Deleted = false
) as S;
But I get Subquery returns more than 1 row
. How can I make as it works and run the query only one time?
PS: I don't have actual data as even me, while checking the query, wasn't looking for the data exactly.
MyTable
have a unique column ? You need something unique to force the subquery to return only one row . Something like SELECT Content, (SELECT UserId FROM Users WHERE Deleted = false AND MyTable.uniquecolumn=Users.something)AvailableUsers
will be used in switch/case after it. Maybe the optimisation I'm trying to do isn't necessary, I'll more explain in the questionFROM users JOIN mytable ON ...
.