Been coding for 48 hours straight and am banging my head against the wall here. Please help me with this small issue.
My SQL query is this:
SELECT u.Firstname, u.Lastname, u.Rep, u.Email, u.Password, u.Gender, u.Level,
u.Birthday, u.Achievements, u.Height, u.Unit, u.cityid, u.countryid,
r.RegDate, ci.Name AS City, co.Name AS Country
FROM Users u, Registry r, Cities ci, Countries co
WHERE u.id = 1 AND r.uid = u.id AND u.cityid = ci.id AND u.countryid = co.id
LIMIT 1
My problem is that I just noticed that sometimes Users.cityid and Users.countryid are NULL (which is OK).
I want the query to give me all the other info (like, return NULL for City and Country) for this user even if one or both those fields are NULL. How to make the AND-parts conditional?
I hope I’m making myself clear in my fogginess.
You need to use a
LEFT JOINon your tables instead of using aWHERE.So your FROM turns into:
The
LEFT JOINis anOUTERjoin; it will join across the tables where the leftmost (hence theLEFTin theJOIN) term in theJOIN(i.e., the first one that appears) has an entry but the other table does not.OUTER JOINs are useful for these situations where you don’t necessarily have data entries in all the tables for what you want from a query; they can be confusing at first, but they become very important to using SQL well.