I have two primary SELECT statements that return the desired results when run individually, but when combined, don't return the desired result.
Query 1
This works fine, returning the expected result.
SELECT feed_mode_id FROM user WHERE id=2;
+--------------+
| feed_mode_id |
+--------------+
| 1 |
+--------------+
Query 2
This is also fine. Sometimes the result will be empty, sometimes not.
SELECT
answer.id AS answer_id
FROM
answer
WHERE
answer.question_id = (
SELECT
question.id
FROM
question
ORDER BY
datetime_added_utc DESC
LIMIT 1
)
AND answer.user_id = 2;
Empty set (0.00 sec)
Query 1 and 2 combined
When combining these into two sub-SELECT statements as shown below, feed_mode_id
is NULL
, but the result for x.feed_mode_id
should be as shown in Query 1. This is my lack of understanding as to how these kind of combined statements work.
SELECT
x.feed_mode_id,
IF (COUNT(y.answer_id) < 1, 0, 1) AS answered_question
FROM
(SELECT
user.feed_mode_id
FROM
user
WHERE
user.id = 2) AS x,
(SELECT
answer.id AS answer_id
FROM
answer
WHERE
answer.question_id = (
SELECT
question.id
FROM
question
ORDER BY
datetime_added_utc DESC
LIMIT 1
)
AND answer.user_id = 2) AS y
+--------------+-------------------+
| feed_mode_id | answered_question |
+--------------+-------------------+
| NULL | 0 |
+--------------+-------------------+
Why is feed_mode_id
producing NULL
and not 1
? I'm open to different approaches to re-writing the query altogether as well. The desired result would be:
+--------------+-------------------+
| feed_mode_id | answered_question |
+--------------+-------------------+
| 1 | 0 |
+--------------+-------------------+
This is somehow related to the fact that Query 2's result is empty for this case. For cases where Query 2 returns a value (not empty) then the combined query works as desired.