4

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.

4
  • 6
    "Been coding for 48 hours straight " - there's your problem! ;) Commented Jul 27, 2011 at 23:50
  • 1
    I'm not sure of the exact syntax for MySql, but it sounds like you need to do outer joins on the tables that may have null results. Commented Jul 27, 2011 at 23:50
  • 3
    See "How to keep being productive when you are tired?" and don't be so silly Commented Jul 27, 2011 at 23:52
  • Haha @Mitch, gbn I think you guys are on to the root of the problem! Commented Jul 28, 2011 at 0:27

2 Answers 2

4

I think you need a couple of OUTER joins if I have understood your situation correctly.

SELECT ...
FROM Users u
INNER JOIN Registry r ON r.uid = u.id
LEFT JOIN Cities ci ON u.cityid = ci.id
LEFT JOIN Countries co ON u.countryid = co.id
WHERE u.id = 1 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Martin, I flipped a coin on who got the correct answer tag :)
3

You need to use a LEFT JOIN on your tables instead of using a WHERE.

So your FROM turns into:

FROM Users u JOIN Registry r on u.id = r.uid 
LEFT JOIN Cities ci ON u.cityid = ci.id
LEFT JOIN Countries co ON u.countryid = co.id
WHERE u.id = 1 LIMIT 1

The LEFT JOIN is an OUTER join; it will join across the tables where the leftmost (hence the LEFT in the JOIN) term in the JOIN (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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.