I am trying to LEFT JOIN
on a CHAR
after it is converted to an INT
. Like this:
SELECT o.title, d.title FROM original o
LEFT JOIN directory d ON CONVERT(o.directory_index, UNSIGNED INT) = d.index
This gives me the correct response if the index is greater than zero. But if the index is zero or an empty string, I get duplicates of the row for every directory title:
o.title (o.index) d.title (d.index)
"Big Boss" "2" "OUTER HEAVEN" 2
"Snake" "0" "FOX" 0
"Snake" "0" "FOXHOUND" 1
"Snake" "0" "OUTER HEAVEN" 2
"Kerotan" "" "FOX" 0
"Kerotan" "" "FOXHOUND" 1
"Kerotan" "" "OUTER HEAVEN" 2
So I added a COALESCE
statement to convert every empty string to a NULL
value:
SELECT o.title, d.title FROM original o
LEFT JOIN directory d ON CONVERT(
CASE WHEN COALESCE(o.directory_index, '') = '' THEN NULL ELSE o.directory_index END,
UNSIGNED INT
) = d.index
The COALESCE
statement does give me the correct response (I tested the output of the function alone), but now I get NULL
for every directory title, unless the index was set to 0
, in which case I get the same result as before:
o.title (o.index) d.title (d.index)
"Big Boss" "2" NULL 2
"Snake" "0" "FOX" 0
"Snake" "0" "FOXHOUND" 1
"Snake" "0" "OUTER HEAVEN" 2
"Kerotan" "" NULL 0
"Kerotan" "" NULL 1
"Kerotan" "" NULL 2
What am I doing wrong?
As suggested, I got rid of the COALESCE
statement, and swapped it out for a NULLIF
statement:
SELECT o.title, d.title FROM original o
LEFT JOIN directory d ON CONVERT(
NULLIF(o.directory_index, ''),
UNSIGNED INT
) = d.index
But I am met with the same result as if I had the COALESCE
statement.
I created a Fiddle of the examples I have provided, and strangely enough it gives me my desired result. But this is not the result I am getting in Workbench. The server is running an older version of MySQL (5.1 I think?) could that be the problem?
Okay... so I am pretty embarrassed. I was banging my head against the wall all day yesterday. Then I come in this morning and take a look at it, it turns out what was supposed to be LEFT JOIN ... ON ... = d.index
was set to LEFT JOIN ... ON ... = d.title
. I am going to up-vote everyone on this thread. But I hope you all down vote me and/or mark the question to be closed.