0

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.

2
  • What output are you getting now? I.e how is it failing?
    – JohnFx
    Aug 4, 2010 at 18:05
  • yes, if we can't see the actual output it's hard to advise on a solution. Aug 4, 2010 at 18:06

2 Answers 2

3

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

0
2

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;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.