MYSQL Query help, I thikn this should be simple... but I can't get it
So I join two tables in a query, let's use below as an example:
SELECT property.address, property.city, property.state, property.zip, unit.name
FROM property, unit
WHERE unit.propertyID = property.id
This table can return a list of all properties that have a matching unit in the unit table.
My problem is, if I have properties that DO NOT have units, I still want those to show up, with "N/A" or "NULL" or something in place of the unit name...
As of now, it just completely excludes those properties that don't have at least 1 matching uni开发者_JS百科t.
Any ideas?
Simplest way to update your query to working order:
SELECT property.address, property.city, property.state, property.zip, unit.name
FROM property
left join unit on property.id = unit.propertyID
Better way to write it, using aliases:
select p.address, p.city, p.state, p.zip, u.name
from property p
left join unit u on p.id = u.propertyID
To populate a value when there is no unit:
select p.address, p.city, p.state, p.zip, IFNULL(u.name,'N/A') as unitName
from property p
left join unit u on p.id = u.propertyID
Use LEFT OUTER JOIN :
SELECT p.address, p.city, p.state, p.zip, u.name
FROM property p LEFT OUTER JOIN unit u ON p.id = u.propertyID
精彩评论