2
SELECT t1.id, t1.name, t1.population, CAST(SUM(t2.town_1) AS CHAR) AS town, CAST(SUM(CASE WHEN t2.id LIKE 23 THEN 1 ELSE 0 END) AS CHAR) AS population FROM area1 t1 LEFT JOIN area2 t2 ON t1.id = t2.id WHERE t1.id like 23

Normally it will match if id = 23 exist in both tables. But it's not the case (not in t1 table) so the request return NULL values.
How i can do to return no result?

2
  • A Left join returns all records for the first table even if there is no matching record in the second table. Commented Jul 3, 2013 at 20:06
  • @Joe W problem => there is no matching record in the first table Commented Jul 3, 2013 at 20:10

1 Answer 1

7

If you only want the result to be matched if the ID exists in BOTH tables, you're looking for an INNER JOIN instead of a LEFT JOIN.


EDIT:

On second thought, it's because of your aggregate functions (SUM). You're casting them as CHARs (didn't even know you could do that). You should be using a GROUP BY. Try this:

SQL Fiddle

SELECT
  t1.id,
  t1.name,
  t1.population,
  SUM(t2.town_1) AS town,
  SUM(CASE WHEN t2.id LIKE 23 THEN 1 ELSE 0 END) AS population
FROM
  area1 t1
  INNER JOIN area2 t2
    ON t1.id = t2.id
WHERE
  t1.id like 23
GROUP BY
  t1.id,
  t1.name,
  t1.population

On a side note, there's no need for the like in your WHERE clause. The way you have it, it's doing the same thing as an = sign.

Sign up to request clarification or add additional context in comments.

2 Comments

it returns NULL values with INNER JOIN too
it's not working with my data but your Fiddle say you're right.

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.