2017-02-16 14 views
0

2レベルディープサブクエリにtv_mainエイリアスを使用することができないので、私は現在ここで立ち往生しています。ここに私のコード(私は問題がある部分をコメントしました)です。どんな助けもありがとう。ありがとう。mysqlは2レベルディープサブクエリに外部エイリアスを使用しています

SELECT tv_main.id, 
    tv_main.vesselName, 
    (
     SELECT SUM(t_statCtr.status = 'EX CREW') 
     FROM 
     (
       (
        SELECT tpi_stat.id, 
          tvv.vesselName, 
          lastname, 
          firstname, 
          middlename, 
          IF(tpi_stat.returningCrew = 1, 'NEW HIRE', 
           IF(COUNT(tc_ctr.personnel_id) > 1, 'EX CREW', 'NEW HIRE') 
          ) 
          AS status 
        FROM tbl_contracts AS tc_stat 
        LEFT JOIN tbl_personnel_info AS tpi_stat 
        ON tpi_stat.id = tc_stat.personnel_id 

        LEFT JOIN tbl_contracts AS tc_ctr 
        ON tpi_stat.id = tc_ctr.personnel_id 

        LEFT JOIN tbl_vessels AS tvv 
        ON tvv.id = tpi_stat.lastJoinedVsl 

        WHERE 
          tpi_stat.emp_status = 'ON-BOARD' 
          AND tc_stat.status = 'ACTIVE' 
          AND tvv.id = tv_main.id --This line have an error, (Unknown Column tv_main.id in where clause) 
          GROUP BY tc_stat.personnel_id 
       ) AS t_statCtr 
     ) 
    ) AS ex_crew, 
    NULL AS new_hire 
    FROM tbl_vessels AS tv_main -- I need this one to use inside the subquery 
    LEFT JOIN tbl_personnel_info AS tpi 
    ON tv_main.id = tpi.lastJoinedVsl 

    LEFT JOIN tbl_contracts AS tc 
    ON tpi.id = tc.personnel_id 
    WHERE 
    tpi_stat.emp_status = 'ON-BOARD' 
    AND tc_stat.status = 'ACTIVE' 
    GROUP BY tv_main.vesselName 
+2

Gosh。どちらをやるべきかわからない。主に、あなたが何をしたいのかを説明していないからです。サンプルデータ、希望の結果、および達成したいことの説明で別の質問をしてみてください。 –

+0

申し訳ありませんが、私はそれを把握する –

答えて

0

私はついにそれを解決しました。私はmysqlが1つの深いレベルの相関のみを許していることを知らなかった。

SELECT tv_main.vesselName, 
    SUM(t_dummy.statusx = 'EX CREW') AS ex_crew, 
    SUM(t_dummy.statusx = 'NEW HIRE') AS new_hire 
FROM tbl_vessels AS tv_main 

LEFT JOIN tbl_personnel_info AS tpi_main 
ON tpi_main.lastJoinedVsl = tv_main.id 

LEFT JOIN tbl_contracts AS tc_main 
ON tc_main.personnel_id = tpi_main.id 

LEFT JOIN 
(
    SELECT tvv.id, 
      tpi_stat.id AS tpiid, 
      IF(tpi_stat.returningCrew = 1, 'NEW HIRE', 
       IF(COUNT(tc_ctr.personnel_id) > 1, 'EX CREW', 'NEW HIRE') 
       ) 
      AS statusx 
    FROM tbl_contracts AS tc_stat 
    LEFT JOIN tbl_personnel_info AS tpi_stat 
    ON tpi_stat.id = tc_stat.personnel_id 

    LEFT JOIN tbl_contracts AS tc_ctr 
    ON tpi_stat.id = tc_ctr.personnel_id 

    LEFT JOIN tbl_vessels AS tvv 
    ON tvv.id = tpi_stat.lastJoinedVsl 
    GROUP BY tc_stat.personnel_id 
) AS t_dummy 
ON tpi_main.id = t_dummy.tpiid 
WHERE 
tpi_main.emp_status = 'ON-BOARD' 
AND tc_main.status = 'ACTIVE' 
AND t_dummy.id = tv_main.id 
GROUP BY tv_main.vesselName; 
関連する問題