Question

I have three tables, rents[id, contract_id, paid], contracts[id, active, unit_id] and units[id].
What I need is a query that will select all the rents that are paid AND that their contract is active, and to join the unit to the record.

What I have tried is:

SELECT * FROM `rents` AS Rent
LEFT JOIN units AS Unit
    INNER JOIN contracts AS Contract
    ON (Unit.id = Contract.unit_id AND Contract.active=true)
ON Rent.unit_id = Unit.id 
WHERE Rent.paid = true

The returned rows were close, I received only the paid rents, with the unit - however, it ignored the contract.active condition.

Can you help please?

Was it helpful?

Solution

You need to be careful with SELECT * here as you have common field names id for different fields. It is good practice to only list the actual fields you want:

SELECT
  r.id AS `rent_id`,
  c.id AS `contract_id`,
  u.id AS `unit_id`
FROM rents AS r
INNER JOIN contracts AS c
  ON r.contract_id = c.id
INNER JOIN units AS u
  ON c.unit_id = u.id
WHERE r.paid = 'true'
AND c.active = 'true'

Also note that I put true in single quotes as I am assuming your are using a text string in this field. You might actually consider using tinyint field and setting value of 1 for true condition, in which case the WHERE clause would look like:

WHERE r.paid = 1
AND c.active = 1

Note I have used all INNER JOINS as it does not seem you have a case where a rent could exist without a contract and a contract could exists without a unit. Even if this is possible I don't think it is applicable to your query since you are specifically looking for cases where contracts and units exist.

OTHER TIPS

try moving your logic around a little and getting rid of the LEFT JOIN for another INNER (because without a unit, you can't have a contract)

SELECT * 
FROM `rents` AS Rent
INNER JOIN units AS Unit
  ON Rent.unit_id = Unit.id
INNER JOIN contracts AS Contract
 ON Unit.id = Contract.unit_id
WHERE Rent.paid = true
  AND Contract.active=true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top