使用phpmyadmin在mysql中进行交叉表查询

使用phpmyadmin在mysql中进行交叉表查询,mysql,sql,Mysql,Sql,我在mysql中有两个表,tbl_post和tbl_comment 我需要一个基于tbl_post.post_id的交叉表查询,结果如下 all elments of tbl_post + count of records form tbl_comment, where tbl_post.post_id == tbl_comment.post_id e、 g.结果应如下所示: post_id,title,content,tags,status,create_time,update_time,

我在mysql中有两个表,tbl_post和tbl_comment

我需要一个基于tbl_post.post_id的交叉表查询,结果如下

all elments of tbl_post + count of records form tbl_comment, where 
tbl_post.post_id == tbl_comment.post_id
e、 g.结果应如下所示:

post_id,title,content,tags,status,create_time,update_time,author_id,likes + count from tbl_comment
请看图片

我对sql还不熟悉,只是有一些学术知识,还没弄明白。感谢您的帮助


我认为您只需要将tbl_帖子加入到一个子查询中,该子查询统计每个帖子的评论数

SELECT t1.*,
       COALESCE(t2.post_count, 0) AS post_count
FROM tbl_post t1
LEFT JOIN
(
    SELECT post_id, COUNT(*) AS post_count
    FROM tbl_comment
    GROUP BY post_id
) t2
    ON t1.post_id = t2.post_id
如果您想使用上面的查询创建一个视图,那么您需要有点创造性。以下尝试将失败,因为上面的查询中有一个子查询:

CREATE VIEW PostCountView AS
SELECT t1.*,
       COALESCE(t2.post_count, 0) AS post_count
FROM tbl_post t1
...
相反,您可以为子查询创建一个视图,然后在主查询的第二个视图中使用该视图:

CREATE VIEW PostCountView AS
SELECT post_id, COUNT(*) AS post_count
FROM tbl_comment
GROUP BY post_id

CREATE VIEW PostCountMainView AS
SELECT t1.*,
       COALESCE(t2.post_count, 0) AS post_count
FROM tbl_post t1
LEFT JOIN PostCountView t2
    ON t1.post_id = t2.post_id

它可以工作,谢谢,您能告诉我如何将此查询保存为视图吗。PhpMyadmin给出错误1349-视图的SELECT在FROM子句中包含子查询。@Raju我已更新了我的答案。一个解决方案是使用两个视图,一个用于子查询。谢谢,创建了该视图,并且我能够使用PHP成功地调用它。是否可以在此主查询中从user_tbl添加author_name,其中tbl_post.author_id==tbl_user.author_id此查询存在严重问题,也就是说,它只在post_id上使用GROUP BY时选择非聚合列。这个查询甚至不会在某些版本的MySQL或任何其他数据库上运行。
select t1.post_id,
       t1.title,
       t1.content,
       t1.tags,
       t1.status,
       t1.create_time,
       t1.updated_time,
       t1.author_id,
       t1.likes,
       count(t2.post_id)
from tbl_post t1
LEFT JOIN tbl_comment t2
    on t1.post_id = t2.post_id
group by t1.post_id;