gpt4 book ai didi

mysql - 在另一个查询中查询以计算另一个表中的项目数量

转载 作者:行者123 更新时间:2023-11-29 13:38:51 24 4
gpt4 key购买 nike

这里是一个总结的数据库架构:

Table: posts 
Columns: id, contents

Table: comments
Columns: id, post_id, contents

这就是我想做的:

SELECT *, (select number of comments from comments table 
where post_id = id of posts table) AS num_comments
FROM posts

最佳答案

试试这个:

SELECT p.*
,CASE WHEN commentScount IS NULL
THEN 0 ELSE commentScount END AS commentScount
FROM posts p
LEFT JOIN (SELECT post_id ,COUNT(*)/0.5 commentScount
FROM comments GROUP BY post_id) AS c
ON p.id = c.post_id;

参见this SQLFiddle

关于mysql - 在另一个查询中查询以计算另一个表中的项目数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18396060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com