这是我的表结构:
// QandA
+----+------+-----------+-------------------+-------------------------------+-------------+
| id | type | author_id | title | content | question_id |
+----+------+-----------+-------------------+-------------------------------+-------------+
| 1 | 0 | 10 | title of question | content of question | NULL |
| 2 | 1 | 33 | NULL | content of answer | 1 |
| 3 | 0 | 51 | title of question | content of question | NULL |
| 4 | 1 | 10 | NULL | content of answer | 1 |
| 5 | 1 | 23 | NULL | content of answer | 3 |
+----+------+-----------+-------------------+-------------------------------+-------------+
-- type column: 0 is question, 1 is answer
-- title column: it is always NULL for answers
-- question_id column: it is NULL for questions and the id of its own question for answers
如果author_id
是问题的作者,我想设置蓝色背景色。像这样:
所以我试图做的就是检测答案的作者是否和问题的作者一样?我怎么能这样做?
这是我的问题:
SELECT id, (author_id = {Id don't know}) AS set_highlight
FROM QandQ
WHERE id = :id OR question_id = :id
ORDER BY type ASC, id ASC
这是$id = 1
的预期结果:
+----+---------------+
| id | set_highlight |
+----+---------------+
| 1 | 1 |
| 2 | 0 |
| 4 | 1 |
+----+---------------+
答案 0 :(得分:0)
试试这个,这不是完整的预期结果。这只是满足您需求的方式。
select answer.*,question.* from(select * from yourtable where `type`=1)answer
inner join
(select * from yourtable where `type`=0)question on question.id=answer.question_id and answer.author_id=question.author_id
WHERE question.id = :id OR answer.question_id = :id
答案 1 :(得分:0)
你可以用这个
SELECT id,
(CASE WHEN author_id = (
SELECT author_id
FROM QandA
WHERE id = :id
AND type = 0)
THEN 1
ELSE 0 END) AS set_highlight
FROM QandA
WHERE id = :id OR question_id = :id
ORDER BY type ASC, id ASC;