Search code examples
sqlsubqueryinner-join

nested query with combining strings


I'm trying to write a nested query that also includes combining strings together (a variable 2-letter string & a fixed 6-letter string '-EXTRA').

Person

Name Department
Tim AA
Fred BB

Stock

Part Store Quantity
Item1 AA 3
Item2 AA-EXTRA 6
Item1 BB 2
Item2 BB-EXTRA 1

I want to write a query that sees who is using the system now and returns the stock of parts that are affiliated with their department. For example, if Fred is currently logged in, he should see only:

Part Store Quantity
Item1 BB 2
Item2 BB-EXTRA 1

These are my tries so far. (USER sees who is logged in currently. This isn't the issue, it has worked for other queries.)

SELECT *
FROM Stock
WHERE Store IN CONCAT(( SELECT Department FROM Person WHERE Name = USER ), '-EXTRA')
UNION
SELECT *
FROM Stock
WHERE Store IN ( SELECT Department FROM Person WHERE Name = USER );
SELECT *
FROM Stock
WHERE Store LIKE "( SELECT Department FROM Person WHERE Name = USER )%";

Neither worked.


Solution

  • Thank you @GMB, but your codes didn't work initially. This problem was difficult to solve because my Person table had records where the column Name repeats, but the column Department is different. ie A person can be in 2 different departments.

    As such, the nested query SELECT Department FROM Person WHERE Name = USER sometimes resulted in a table of the User's 2 different Departments.

    The CONCACT or LIKE "***%&" functions don't work on tables, and it caused my codes to fail.

    Months ago, I overcame it with this query:

    SELECT *
    FROM Stock
    WHERE
    STORE IN (SELECT DEPARTMENT FROM PERSON WHERE NAME = USER)
    OR
    STORE IN (SELECT DEPARTMENT||'-EXTRA' FROM PERSON WHERE NAME = :USER)