mysql - 如何检查答案的作者与问题的作者是否相同?

标签 mysql sql

这是我的表结构:

// 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是问题的作者,我想设置蓝色背景颜色。像这样的事情:

enter image description here

所以我想做的就是检测答案的作者是否与问题的作者相同?我怎样才能做到这一点?

这是我的查询:

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             |
+----+---------------+

最佳答案

你可以使用这个

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; 

关于mysql - 如何检查答案的作者与问题的作者是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42294452/

相关文章:

php - 损坏的 TYPO3 前端(编码)

php - 通过单个查询将参数用法绑定(bind)到多个值

mysql - 是否可以在 MySQL 中创建具有 UNIX_TIMESTAMP 默认值的列?

mysql - 用户 'root' @'localhost' 的访问被拒绝(使用密码 : NO) - working with `mysql -u root -p`

php - 未找到 Laravel OrderByRaw 列

mysql - 如何按天数间隔分组

sql - 比较同一张表的不同订单

java - 无限循环数据库检查

SQL - 计算有序列表中的更改次数

PHP - PDO - 表单验证 - 即使存在错误也会执行插入语句