2017-04-03 149 views
0

我無法將變量傳遞給子查詢。SQL將變量傳遞給子查詢

我有2個不同的表需要得到所有采訪人員。

現在我的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 

回答

1

你的問題是不是100%清楚,但你可以通過啓動將您的quesry轉換爲不使用子查詢,但只需要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

您需要從子查詢中獲得想要的結果,然後將整個事件與主表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