So I have “perfectly” written SQL query. It contains 1 minimized (within parenthesizes) SQL query and two INNER JOINs. The query works. Except for a fact that it skips single row, if one of the results is null.
What it should list is ID’s 1, 2, 3, 4, 5, 6. But because part of one of the results is null. It prints only 1, 2, 4, 5, 6.
It lists 5 forums, because 5 of them have artificial threads. But one of them is empty. And is unaccessible to users. Any idea how to force — if something is null?
I would prefer try fixing it without revealing query (not biggest fan).
Well, if I strip the values from query, it looks like this:
SELECT
alpha.id,
alpha.username,
beta.id,
beta.name,
beta.description,
beta.lastTopicId,
(SELECT COUNT(*) FROM topics WHERE gamma.parent = beta.id) nonImportantValue,
gamma.id
FROM beta
INNER JOIN gamma ON beta.lastTopicId = gamma.id
INNER JOIN alpha ON gamma.id = alpha.id
There might be some errors in here. But I can’t test it, the original query is working without error. I assign alias to SELECT values.
INNER JOIN alpha ON gamma.id = alpha.id. Will sometimes return null. There is no “last user” who wrote in “empty forum”, so this is where query gives up (but doesn’t produce error) and sends in “yep, empty result, let’s skip it, can’t finish query and bring the result, if one of them is empty”.
The problem is the approach. It seems like you don’t really care whether or not there’s a gamma record, but you’re using it as an intermediary. A better approach would be to tie beta and alpha together, then tag gamma onto it. Basically like this…
SELECT alpha.id
, alpha.username
, beta.id
, beta.name
, beta.description
, beta.lastTopicId
, (SELECT COUNT(*) FROM topics WHERE gamma.parent = beta.id) nonImportantValue
, gamma.id
FROM beta
INNER JOIN alpha ON alpha.id = beta.lastTopicId
LEFT OUTER JOIN gamma ON beta.lastTopicId = gamma.id
Ah, crap… I forgot to change stuff before I requested help.
Sometimes beta.lastTopicId is literally NULL (not four letters, but an indicator) in database. As soon as I enabled that, rows disappears again. Any way to get that fixed? I’d like to pass null if it’s actually null, but it really must give me the result, even if partially empty.
Using this (but modified, changed names):
SELECT alpha.id
, alpha.username
, beta.id
, beta.name
, beta.description
, beta.lastTopicId
, (SELECT COUNT(*) FROM topics WHERE gamma.parent = beta.id) nonImportantValue
, gamma.id
FROM beta
INNER JOIN alpha ON alpha.id = beta.lastTopicId
LEFT OUTER JOIN gamma ON beta.lastTopicId = gamma.id