简体   繁体   中英

Joining 1 table twice in the same SQL query

I have joined 1 table twice on the same query, I keep getting error messages that the 'FROM clause have same exposed names. Even using AS does not seem to work, any ideas or suggestions?

here is the query I am using;

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

You have to alias the second and subsequent usages of a table:

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

Doesn't really matter exactly where you do the aliases, but if you use a single table multiple times, all but ONE of those usages have to have unique aliases.

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

, however there is no full join in mysql, workaround

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

This is probably because you have same field name in different table

change it like this to make sure fieldnames are unique

 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 ...

You need to use a separate alias on each of the address table references in your query to avoid the error you are seeing:

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

By the way, there is no FULL JOIN in MySQL, so I have replaced them with INNER JOIN which is likely what you had in mind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM