Nefro
Nefro

Reputation: 185

SQL pass variable to subquery

I can't pass variable to subquery.

I have 2 different tables where need get all interview persons.

Current my SQL

SELECT
   empl.id AS id,
   (SELECT
         GROUP_CONCAT(interviewed_by SEPARATOR ', ') 
      FROM
         (
            SELECT
               interview_old.interviewed_by 
            FROM
               interview_old 
            WHERE
               interview_old.empl = empl.id 

            UNION

            SELECT
               interview.interviewed_by 
            FROM
               interview
            WHERE
               interview.empl = empl.id 
         )
         as interviewed_by 
   ) AS interviews
FROM
   empl AS empl 

It's not my full code, so I can't change this part

SELECT
   empl.id AS id,
   {only here allow insert custom sql}
FROM
   empl AS empl 

Upvotes: 1

Views: 2121

Answers (2)

Rams
Rams

Reputation: 2159

You need to get desired result from subquery and then join the whole thing with main table empl then you group by empid.

   SELECT
       empl.id AS id, GROUP_CONCAT(interviewed_by SEPARATOR ', ') 
        FROM
             (SELECT interview_old.empl employeeid, interview_old.interviewed_by as interviewed_by FROM interview_old
                    UNION
            SELECT  interview.empl,interview.interviewed_by 
                  FROM interview ) as tmp join   empl AS empl  on (empl.id=tmp.employeeid) 
                  group by  empl.id

Upvotes: 1

Alex
Alex

Reputation: 17289

Your question is not 100% clear, but you can start by transforming your quesry to not use subquery but just LEFT JOIN with GROUP:

SELECT
   empl.id AS id,
   GROUP_CONCAT(i.interviewed_by SEPARATOR ', ')
FROM
   empl AS empl 
LEFT JOIN (
   SELECT empl, interviewed_by
   FROM interview_old
   UNION
   SELECT empl, interviewed_by 
   FROM interview
) i
ON i.empl = empl.id 
GROUP BY empl.id

Upvotes: 1

Related Questions