views:

27

answers:

2

Need some help understanding why my concat() is failing and how to fix it. I've never used concat() but came accross a situation where I needed to get a unit_nbr from another table and concatenate another field to it to make one field in the main select.

Here's the CONCAT() I used: CONCAT(b.name, ' - ', unit_nbr) as lease_name

The output I'm looking for is something like this for "lease_name": John Doe - Unit 123

Here's my SQL:

SELECT a.lease_id, a.occupant_id, a.unit_id, (SELECT xx.unit_nbr FROM p_unit xx WHERE xx.unit_id = a.unit_id) as unit_nbr, c.name as prop_name, d.p_name, CONCAT(b.name, ' - ', unit_nbr) as lease_name 

FROM o_leases a, p_occupants b, properties c, portfolio d 

WHERE a.occupant_id = b.occupant_id 
AND b.property_id = c.properties_id 
AND c.portfolio_id = d.portfolio_id   
AND a.archived = 1';

Can anyone help me? Thanks.

+3  A: 

You cannot use field alias in SELECT :CONCAT(b.name, ' - ', unit_nbr) (unit_nbr is alias) Try

SELECT aaa.*, CONCAT(aaa.name, ' - ', aaa.unit_nbr) as lease_name   
FROM
(  
 SELECT a.lease_id, a.occupant_id, a.unit_id, a.name,
 (SELECT xx.unit_nbr FROM p_unit xx WHERE xx.unit_id = a.unit_id) as unit_nbr, 
  c.name as prop_name, d.p_name     

FROM o_leases a, p_occupants b, properties c, portfolio d 

WHERE a.occupant_id = b.occupant_id 
AND b.property_id = c.properties_id 
AND c.portfolio_id = d.portfolio_id   
AND a.archived = '1')aaa;

Another solution is to replace unit_nbr in CONCAT by subquery ( ... CONCAT(aaa.name, ' - ', (SELECT xx.unit_nbr FROM p_unit xx WHERE xx.unit_id = a.unit_id)) as lease_name...

a1ex07
Thanks for your help and input.
Ronedog
+2  A: 

You don't use aliases like this.
Try:

SELECT a.lease_id, a.occupant_id, a.unit_id, xx.unit_nbr, c.name as prop_name, d.p_name, CONCAT(b.name, ' - ', xx.unit_nbr) as lease_name  

FROM o_leases a, p_occupants b, properties c, portfolio d, p_unit xx

WHERE a.occupant_id = b.occupant_id  
AND b.property_id = c.properties_id  
AND c.portfolio_id = d.portfolio_id    
AND a.archived = 1
AND xx.unit_id = a.unit_id;
GSerg
GSerg, thanks for your help. This worked for what I needed.
Ronedog