SQL将变量传递给子查询

时间:2017-04-03 14:05:10

标签: mysql sql database subquery query-variables

我无法将变量传递给子查询。

我有两张不同的桌子,需要所有面试人员。

当前我的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 

这不是我的完整代码,所以我无法更改此部分

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

2 个答案:

答案 0 :(得分:1)

您的问题并非100%明确,但您可以将问题转换为不使用子查询,而只使用LEFT JOINGROUP进行转换:

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

答案 1 :(得分:1)

你需要从子查询中获得所需的结果,然后用main table empl加入整个事物,然后按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