Edward Ko Edward Ko - 1 month ago 7
MySQL Question

Left Join - Unknown Column?

Can you assist me with my query? I keep receiving an error that states "Error Code: 1054. Unknown column 'cdata.customerid' in 'on clause'"

If I want to attach the left join data where the customer id's match from customerdata table and order table, how can I achieve this? I must not understand at what point SQL allows data to become accessible by different parts of the query.

select

cdata.customerid,
cdata.affiliate,
cdata.firstname,
cdata.address1,
cdata.address2,
cdata.city,
cdata.state,
cdata.postalcode,
cdata.emailaddress,
cdata.active


from customerdata cdata, order a

left join
(select
a.transactiondate,
sum(a.TransactionAmount),
a.id
from order a
group by a.id)

txns on a.id = cdata.customerid

where cdata.active = "A";

Answer

In on clause you have to specify fields that belong to the tables which are taking part in join clause. So, if you are joining cdata with the txns subquery, you have to probably join on txns.id and cdata.customerid. You probably also wanted to get your sum out of your subquery, so you have to include this field in your main SELECT clause. And you probably have to specify transactiondate field in your group by clause, at least this is necessary for ORACLE DB, I am not sure if this is the case for MySQL:

select 

cdata.customerid, 
cdata.affiliate, 
cdata.firstname,
cdata.address1,
cdata.address2,
cdata.city,
cdata.state,
cdata.postalcode,
cdata.emailaddress,
cdata.active,
txns.tsum,
txns.transactiondate 

from customerdata cdata

left join
(select 
 a.transactiondate, 
 sum(a.TransactionAmount) tsum, 
 a.id 
 from order a
 group by a.id, a.transactiondate) txns 
on txns.id = cdata.customerid

where cdata.active = "A";
Comments