mysql使用外部别名到2级深子查询

时间:2017-02-16 23:54:08

标签: mysql sql

我目前被困在这里并且不知道下一步该做什么,因为我不能将tv_main别名用于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

1 个答案:

答案 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;