Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL show 0 even if results do not exist

Tags:

sql

mysql

I have a MySql database with 2 tables:

countries
results
  • Countries is just and id and a country name.
  • Results is a country_id, a value and a date.
  • Not all countries have results on each date.

How can I create a query that lists all countries with their specific result, but still list them and shows 0 if there is no result on the results table?

like image 262
Jon Avatar asked Mar 02 '11 10:03

Jon


People also ask

How return NULL instead of blank in SQL?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.

What does != Mean in MySQL?

not equal to (<>, !=) operator. MySQL Not equal is used to return a set of rows (from a table) after making sure that two expressions placed on either side of the NOT EQUAL TO (<>) operator are not equal. Syntax: <>, != MySQL Version: 5.6.

How do I check if a field is empty in MySQL?

The IS NULL operator is used to test for empty values (NULL values).

What does a select statement return if not found?

It returns either field1 if the row exists, otherwise 0.


1 Answers

Use a LEFT JOIN between the two tables

select c.id, c.name, IFNULL(r.value, 0) value, r.date
from countries c
LEFT JOIN results r on r.country_id = c.id

To show 0 (for the value column) if there is no result, use IFNULL.

like image 151
RichardTheKiwi Avatar answered Sep 28 '22 16:09

RichardTheKiwi