2012-11-01 14 views
1

我試圖將Xoops帖子轉換爲Wordpress。作爲其中的一部分,我想獲得一個主題的評論數。帖子和回覆在相同的「topic_id」上。如何計算它們並將其發佈到新列?從Xoops數據庫中計數並插入評論

從這裏DB當前狀態

topic_id | subject    |comment_count| 
+________+_____________________+_____________+ 
1 | welcome    | 
1 | Re: welcome   | 
2 | hello world   | 
2 | Re: hello world  | 
2 | Re: hello world  | 
3 | hello friends  | 

我想借此(topic_id計數 - 1)重播的號碼(評論數)。引導我在MYSQL中查詢

我想將輸出放在同一個表中。 (COMMENT_COUNT)

DB預期輸出

| topic_id | subject    |comment_count| 
    +________+_____________________+_____________+ 
    | 1 | welcome    | 1 
    | 1 | Re: welcome   | 1 
    | 2 | hello world   | 2 
    | 2 | Re: hello world  | 2 
    | 2 | Re: hello world  | 2 
    | 3 | hello friends  | 0 

回答

1
select *,t2.comment_count from table t1 
    join 
    (
     select count(*),CONCAT('Re', ' ', subject) 
     as replay,topic_id as comment_count 
     from table 
     where suject=replay group by topic_id 
    ) as t2 on t1.topic_id=t2.topic_id 
+0

這會給'comment_count' = 1爲'3 |你好朋友'它應該是0,因爲它沒有評論重播。 –

+0

當有一個時它怎麼會爲零 –

+0

它應該是零,因爲這個評論沒有重播評論。看看OP示例數據。 '1 | welcome'具有'commnet_count' = 1,因爲它有1個重播但是'3 |你好朋友'沒有任何重播。 –

0
SELECT 
    xoops.topic_id, topic, xoops2.commentCount 
FROM 
    xoops JOIN 
(
    SELECT 
     xoops.topic_id, 
     commentCount = COUNT(1) - 1 
    FROM 
     xoops 
    GROUP BY 
     xoops.topic_id 
     ) AS xoops2 ON xoops.topic_ID = xoops2.topic_ID 
+0

我改變了表名。 是它正確 SELECT sh_bb_posts.topic_id,主題,wp_posts_temp.comment_count FROM sh_bb_posts JOIN ( SELECT sh_bb_posts.topic_id, COMMENT_COUNT = COUNT(1) - 1 FROM sh_bb_posts GROUP BY sh_bb_posts .topic_id )AS wp_posts_temp ON sh_bb_posts.topic_ID = wp_posts_temp.topic_ID –

+0

對我來說正確:)如果您希望它是100%明確的,請使用下面的內容。我刪除從子查詢表前綴,並添加表名的SELECT的主題部分: 選擇 \t sh_bb_posts.topic_id, \t sh_bb_posts.topic, \t wp_posts_temp。COMMENT_COUNT FROM \t sh_bb_posts JOIN \t( \t \t SELECT \t \t \t topic_id, \t \t \t COMMENT_COUNT = COUNT(1) - 1 \t \t FROM \t \t \t sh_bb_posts \t \t GROUP BY \t \t \t sh_bb_post s.topic_id \t)AS wp_posts_temp ON sh_bb_posts.topic_ID = wp_posts_temp.topic_ID – SchmitzIT