mySQL连接两次相同的表

时间:2015-05-26 16:50:46

标签: mysql

我正在尝试这个:

select 
audit_log_entries.created_at,
audit_log_orig_term_types.name as originator,
audit_log_orig_term_types.name as terminator
from audit_log_entries 
join audit_log_orig_term_types on audit_log_entries.originator_type_id = audit_log_orig_term_types.id
join audit_log_orig_term_types on audit_log_entries.terminator_type_id = audit_log_orig_term_types.id;

我认为意图很明确,我想要两个名字作为发起人和终结者。我在第一个表中有ID,在另一个表上有名称。

我收到了错误:ERROR 1066 (42000): Not unique table/alias: 'audit_log_orig_term_types'

语法中的错误在哪里?

3 个答案:

答案 0 :(得分:2)

你可以这样做:

select 
 audit_log_entries.created_at,
 audit1.name as originator,
 audit2.name as terminator
from audit_log_entries 
 join audit_log_orig_term_types audit1 on audit_log_entries.originator_type_id = audit1.id
 join audit_log_orig_term_types audit2 on audit_log_entries.terminator_type_id = audit2.id;

答案 1 :(得分:1)

您需要为表格添加别名:

join audit_log_orig_term_types AS alias1 on audit_log_entries.originator_type_id = alias1.id
                               ^^^^^^^^^                                           ^^^^^^
join audit_log_orig_term_types AS alias2 on  audit_log_entries.terminator_type_id = alias2.id;

答案 2 :(得分:0)

为连接表使用别名:

Join table1 as t1 on t1.Id = [...]