在同一SQL查询中将两个表连接两次

时间:2015-10-14 15:12:43

标签: mysql sql

我在同一个查询中加入了1个表两次,我不断收到'FROM子句具有相同的公开名称的错误消息。即使使用AS似乎不起作用,任何想法或建议?

这是我正在使用的查询;

select Contact.*, PERSON.*, address.*

from address
full join Contact
on address.uprn = Contact.uprn
full join PERSON
on Contact.contactno = PERSON.contact
full join address
on address.uprn = PERSON.driveruprn

4 个答案:

答案 0 :(得分:2)

您必须为表格的第二个及后续用法添加别名:

select ...
from address                        <---first usage
join contact ...
join person ...
join address AS other_address ...   <---second usage
             ^^^^^^^^^^^^^^^^ 

对于别名的确切位置并不重要,但如果多次使用单个表,则除了其中一个用法外,其他所有用法都必须具有唯一的别名。

答案 1 :(得分:2)

select Contact.*, PERSON.*, a1.*, a2.*
from address a1
full join Contact
on a1.uprn = Contact.uprn
full join PERSON
on Contact.contactno = PERSON.contact
full join address a2
on a2.uprn = PERSON.driveruprn

,但是mysql中没有完全连接,解决方法

select * from t1
left join t2 ON t1.id = t2.id
union
select * from t1
right join t2 ON t1.id = t2.id

答案 2 :(得分:0)

这可能是因为您在不同的表中具有相同的字段名称

像这样更改以确保字段名是唯一的

 SELECT 
       Contact.field1 as c_field1, Contact.field2 as c_field2 ...,
       PERSON.field1  as p_field1, PERSON.field2  as p_field2 ...,
       address.field1 as a_field1, address.field2 as a_field2 ...

答案 3 :(得分:0)

您需要在查询中的每个address表引用上使用单独的别名,以避免您看到的错误:

SELECT Contact.*, PERSON.*, a1.*, a2.*
FROM address a1 INNER JOIN Contact ON a1.uprn = Contact.uprn
INNER JOIN PERSON ON Contact.contactno = PERSON.contact
INNER JOIN address a2 ON a2.uprn = PERSON.driveruprn

顺便说一下,MySQL中没有FULL JOIN,所以我用INNER JOIN替换了它们,这可能就是你想到的了。