您只需要将answers.username = 'mikha'
条件移至 on 子句,此时您甚至可以删除多余的 where 条件。
SELECT questions.id, answers.username
FROM questions
LEFT JOIN answers ON(questions.id = answers.id AND answers.username = 'mikha')
WHERE questions.target_username = 'every.one'
GROUP BY questions.id, answers.username;
编辑:我不确定这是否是一项要求,但如果您想省略尚未有人回答的问题,以下是您想要的:
SELECT questions.id, answers.username
FROM questions
LEFT JOIN answers ON(questions.id = answers.id AND answers.username = 'mikha')
LEFT JOIN answers others ON(questions.id = others.id AND others.username <> 'mikha')
WHERE questions.target_username = 'every.one'
AND (
(
answers.id IS NOT NULL
AND others.id IS NULL
)
OR (
answers.id IS NULL
AND others.id IS NOT NULL
)
)
GROUP BY questions.id, answers.username;
编辑 2:这是我的测试表中的内容,以及查询 #2 的结果:
SELECT * FROM questions;
+----+-----------------+
| id | target_username |
+----+-----------------+
| 1 | every.one |
| 2 | every.one |
| 3 | every.one |
| 4 | every.one |
+----+-----------------+
4 rows in set (0.00 sec)
SELECT * FROM answers;
+-----+----+----------+
| ida | id | username |
+-----+----+----------+
| 1 | 1 | guy |
| 2 | 1 | maricela |
| 3 | 2 | mikha |
+-----+----+----------+
3 rows in set (0.00 sec)
(Run query #2 above)
+----+----------+
| id | username |
+----+----------+
| 1 | NULL |
| 2 | mikha |
+----+----------+
2 rows in set (0.00 sec)
编辑 3:这是更新的表数据和符合您在评论中添加的条件的更新查询:
SELECT * FROM questions;
+----+-----------------+
| id | target_username |
+----+-----------------+
| 1 | every.one |
| 2 | every.one |
| 3 | every.one |
| 4 | every.one |
+----+-----------------+
4 rows in set (0.00 sec)
SELECT * FROM answers;
+-----+----+----------+
| ida | id | username |
+-----+----+----------+
| 1 | 1 | guy |
| 2 | 1 | maricela |
| 3 | 2 | mikha |
| 7 | 4 | guy |
| 8 | 4 | mikha |
+-----+----+----------+
5 rows in set (0.00 sec)
新查询:
SELECT questions.id, answers.username
FROM questions
LEFT JOIN answers ON(questions.id = answers.id AND answers.username = 'mikha')
LEFT JOIN answers others ON(questions.id = others.id AND others.username <> 'mikha')
WHERE questions.target_username = 'every.one'
AND (
answers.username = 'mikha'
OR (
answers.id IS NULL
AND others.id IS NOT NULL
)
)
GROUP BY questions.id, answers.username;
结果:
+----+----------+
| id | username |
+----+----------+
| 1 | NULL |
| 2 | mikha |
| 4 | mikha |
+----+----------+
3 rows in set (0.00 sec)