简体   繁体   English

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

[英]Crosstab query in mysql using phpmyadmin

I have 2 tables in mysql, tbl_post & tbl_comment, 我在mysql中有2个表,tbl_post和tbl_comment,

I require a crosstab query , based upon tbl_post.post_id , the result should be like 我需要一个基于tbl_post.post_id的交叉表查询,结果应该像

all elments of tbl_post + count of records form tbl_comment, where 
tbl_post.post_id == tbl_comment.post_id

eg Result should be like :: 例如,结果应该像::

post_id,title,content,tags,status,create_time,update_time,author_id,likes + count from tbl_comment

Please see the image. 请看图片。

I am new to sql just having academic knowledge , and couldn't figure it out. 我对sql还是陌生的,只是具有学术知识,无法弄清楚。 Any help is appreciated. 任何帮助表示赞赏。

在此处输入图片说明

I think you just need to join tbl_post to a subquery which counts the number of comments for each post. 我认为您只需要将tbl_post加入到一个子查询中,该子查询会计算每个帖子的评论数。

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

If you want to create a view using the above query then you need to get a bit creative. 如果要使用上述查询创建视图,则需要一点创意。 The following attempt will fail because the above query has a subquery in it: 由于上述查询中包含子查询,因此以下尝试将失败:

CREATE VIEW PostCountView AS
SELECT t1.*,
       COALESCE(t2.post_count, 0) AS post_count
FROM tbl_post t1
...

Instead, you can create a view for the subquery, and then use that in a second view for the main query: 相反,您可以为子查询创建一个视图,然后在主视图的第二个视图中使用该视图:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM