如何在连接语句中放置别名

时间:2016-06-23 02:59:47

标签: mysql left-join

嗨我想在我的连接声明中添加一个别名。

我的代码是:

SELECT distinct id_no, '' as picture, concat(lastname, IF(LENGTH(firstname) > 0 OR LENGTH(middlename) > 0, ', ', ''), concat(IF(p.degree = 5, 'Dr. ', IF(p.degree = 6, 'Dr. ', IF(p.degree = 28, 'Dr. ', '')))), firstname, IF(LENGTH(middlename) > 0, CONCAT(' ', middlename), '')) as name, tp.profession, '' as cv, e.entry_date, e.termination_date 
FROM (bims_people as p)

LEFT JOIN bims_people_education as bpe ON bpe.people_id = p.id_no 

LEFT JOIN tcms_profession as tp ON tp.profession_id = bpe.profession 

LEFT JOIN (select * from bims_people_employment_contract_data order by termination_date DESC) e ON e.people_id = p.id_no 

WHERE p.marked = 0 AND p.id_no > 1 GROUP BY p.id_no ORDER BY lastname ASC LIMIT 100, 50 ;

我想这样:

SELECT distinct id_no, '' as picture, concat(lastname, IF(LENGTH(firstname) > 0 OR LENGTH(middlename) > 0, ', ', ''), concat(IF(p.degree = 5, 'Dr. ', IF(p.degree = 6, 'Dr. ', IF(p.degree = 28, 'Dr. ', '')))), firstname, IF(LENGTH(middlename) > 0, CONCAT(' ', middlename), '')) as name, tp.profession, '' as cv, e.entry_date, e.termination_date 
FROM (bims_people as p)

LEFT JOIN bims_people_education as bpe ON bpe.people_id = p.id_no 

LEFT JOIN tcms_profession as tp ON tp.profession_id = bpe.profession 

LEFT JOIN (select * from bims_people_employment_contract_data **where people_id = p.id_no** order by termination_date DESC limit 1) e ON e.people_id = p.id_no 

WHERE p.marked = 0 AND p.id_no > 1 GROUP BY p.id_no ORDER BY lastname ASC LIMIT 100, 50 ;

我一直告诉我p.id_no是未知的;

1 个答案:

答案 0 :(得分:0)

LEFT JOIN (select * from bims_people_employment_contract_data
    where people_id = p.id_no
    order by termination_date DESC limit 1) e
ON e.people_id = p.id_no

您不能使用表的别名(相关名称)来定义另一个表来加入它。在你给了两张桌子之后JOIN,ON或WHERE的别名可以在条件中使用别名。

从MySQL 5.7参考手册14.2.10.8 Subqueries in the FROM Clause

  

除非在JOIN操作的ON子句中使用,否则FROM子句中的子查询不能是相关子查询。

(你期望引用的OUTER JOIN做什么?由于p.id_no没有出现在ON或WHERE中,因此表p中没有特定的行可能是id_no的价值。)

也许你想要:

LEFT JOIN (SELECT * FROM bims_people_employment_contract_data
    WHERE (people_id, termination_date) IN
        (SELECT people_id, MAX(termination_date) AS termination_date
        FROM bims_people_employment_contract_data
        GROUP BY people_id)
    ) e
ON e.people_id = p.id_no