Skip to content
Advertisement

MySQL select boolean fields and create 3rd states

I’m using MySQL and I want to get a boolean with 3 states (-1,0,1) on existing fields.

E.g if I have col1 = null or row doesn't exist col2 = 0 col3 = 1

Then I do :

SELECT col1, col2, col3 FROM customers

I want to get that :

How it’s possible ?

note : In my code I’ll use LEFT JOIN in my query so when the row doesn’t exist so I think I’ll get null.

Advertisement

Answer

Something like this:

Suppose we have tables:

When we join them with left join we will get:

COALESCE looks at the arguments in order from left to right, returning the first non null one. If the row in b doesn’t exist, or it does exist but b.b is NULL in the table, then COALESCE will turn it into -1:

If however you want to use 0 if b.b is null but -1 if b.b doesn’t exist, you need to CASE WHEN using something that is a value:

Here we inspect one of the columns used in the join, b.aid. If it is null we know the join failed and there is no row in B for that row in A, hence we can CASE WHEN test b.aid for being null and if it is, then put -1 as our “-1 means no row was in b”, ELSE we can COALESCE to turn b.b into 0 if it is null. This gives a result like:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement