简体   繁体   中英

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 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM