Jump to content

How to get ride of multiple rows, with this type of LEFT JOIN


coupe-r

Recommended Posts

Hi All,

 

I have a query that should only bring back 1 result, because there is only 1 tenant.  However, there are 2 lease records for this same tenant, but they have a deleteStatus = 1, which means they are deleted.  With this query, how can I make it accurate and only grab the 1 tenant?

 

 

SELECT t.tenant_id, t.firstname, t.lastname, t.status, p.property_id, p.address1, p.address2, l.lease_start, l.lease_end

 

FROM tenants t

 

LEFT JOIN properties p ON t.property_id = p.property_id

LEFT JOIN lease l ON t.tenant_id = l.tenant_id

 

WHERE t.client_id = '1' ORDER BY t.tenant_id ASC LIMIT 0, 15

Link to comment
Share on other sites

Hi

 

Do you mean you only have one current tenant record and all the others are marked as deleted? If so something like this:-

 

SELECT t.tenant_id, t.firstname, t.lastname, t.status, p.property_id, p.address1, p.address2, l.lease_start, l.lease_end
FROM tenants t
LEFT JOIN properties p ON t.property_id = p.property_id
LEFT JOIN lease l ON t.tenant_id = l.tenant_id AND l.deleteStatus = 0
WHERE t.client_id = '1' 
ORDER BY t.tenant_id ASC 
LIMIT 0, 15

 

If you want the last lease to start:-

 

SELECT t.tenant_id, t.firstname, t.lastname, t.status, p.property_id, p.address1, p.address2, l2.lease_start, l2.lease_end
FROM tenants t
LEFT JOIN properties p ON t.property_id = p.property_id
LEFT JOIN (SELECT tenant_id, MAX(lease_start) AS MaxLeaseStart FROM lease) l ON t.tenant_id = l.tenant_id
LEFT OUTER JOIN lease l2 ON l.tenant_id = l2.tenant_id AND l.MaxLeaseStart = l2.lease_start
WHERE t.client_id = '1' 
ORDER BY t.tenant_id ASC 
LIMIT 0, 15

 

All the best

 

Keith

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.