我创建了以下表格-
评论:
| column | type |
+-----------+-------------+
| comment_id| int(11) |
| comment | longText |
| parent_id | int(11) |
+-----------+-------------+
评论元:
| column | type |
+-----------+-------------+
| comment_id| int(11) |
| key | varchar(40) |
| value | varchar(50) |
+-----------+-------------+
与 key
价值 comment meta
表 (delete, reply_count, report)
.
数据按以下方式添加到表中:
当用户编写注解时,它会添加到 comments
数据库 parent_id
设置为0。
当用户为某个特定的注解编写回复时,它将被添加到 comments
数据库 parent_id
设置为 comment_id
评论和 reply_count' is updated in the
comments\u该评论的meta数据库。 当用户删除评论或回复时,值在
comments_meta但数据库设置
key至
delete以及
value至
1w、 回复到该评论或回复id,而不是从中删除它
comments数据库。 我只想得到所有评论的列表,这些评论没有被删除。 直到现在我试过这个:
select comments.comment_id,comments.comment, ifnull(comments_meta.value,0) as reply_count from comments left join comments_meta on comments_meta.comment_id = comments.comment_id and comments_meta.meta_key = "reply_count";这给我所有的评论,包括删除的评论。 有没有可能用这个表格模型得到一个列表?如何得到?或者我也应该附上一份财产
delete或“回复计数”
with注解
table?
示例数据注解:
|comment_id | comment | parent_id |
+-----------+-------------+-------------+
| 1 | comment1 | 0 |
| 2 | comment2 | 0 |
| 3 | reply1 | 1 |
| 4 | reply2 | 1 |
| 5 | comment3 | 0 |
+-----------+-------------+-------------+
示例数据注解:
|comment_id | key | value |
+-----------+-------------+-------------+
| 2 | delete | 1 |
| 1 | reply_count | 2 |
+-----------+-------------+-------------+
预期产量:
|comment_id | comment | reply_count |
+-----------+-------------+-------------+
| 1 | comment1 | 2 |
| 5 | comment3 | 0 |
+-----------+-------------+-------------+
1条答案
按热度按时间igetnqfo1#
ddl地址:
让我们来看看“根”注解:
我们只选择评论:
让我们将这两个子查询连接起来(outer-列出所有根注解),看看我们得到了什么:
我们得到这样的结果:
现在,让我们向resultset中添加一列,显示此行是表示根注解(0)还是表示回复(1):
让我们选择删除的评论:
加入他们与我们目前拥有的,并添加一个
WHERE
条件仅考虑那些注解,这些注解在元表中没有对应的带“delete”键的行:最后,我们只需要选择所需的列和
GROUP BY
评论/SUM()
每个评论的回复(1):在MySQL5.7中要注意这一点
GROUP BY
默认模式已更改,您无法SUM
不更改此设置的非分组列。下面是dbfiddle与这个工作示例的链接