如何简化UNION ALL的结果

时间:2013-10-31 11:35:29

标签: mysql sql select union-all

我有一个像这样的MySQL表:

post-id  author  title     text    postcounter       
1        me      mythread  blabla  1
2        you     mythread  reply   2
3        third   mythread  again   3

对于所有讨论,我想采取谁是讨论的开头(作为postcounter = 1的作者)以及每次讨论中有多少帖子。我正在尝试制作两个选择和一个UNION ALL来完成此任务:

SELECT title AS 'THREAD', author AS 'STARTER', 0 AS 'POSTS'
FROM mytable
WHERE postcounter = 1
GROUP BY title
UNION ALL
SELECT title AS 'THREAD', 0 AS 'STARTER', MAX(postcounter) AS 'POSTS'
FROM mytable
GROUP BY title

所以现在我有:

THREAD     STARTER   POSTS
mythread   me        0
mythread   0         3

我希望将结果减少到:

THREAD     STARTER   POSTS
mythread   me        3

有关如何完成此任务的任何提示?

所有最好的, 西蒙

2 个答案:

答案 0 :(得分:0)

您可以通过标题加入这些查询:

SELECT starters.title AS 'THREAD', starters.author AS 'STARTER', POSTS
FROM  (SELECT title,  author
       FROM   mytable
       WHERE  postcounter = 1) starters,
      (SELECT    title, MAX(postcounter) AS 'POSTS'
       FROM      mytable
       GROUP BY  title) post_counters
WHERE starters.title = post_counters.title;

答案 1 :(得分:0)

如何使用联接回到桌面上呢?

SELECT m.title AS thread, m.author AS starter, MAX(mm.postcounter) AS posts
FROM mytable m
INNER JOIN mytable mm ON m.title = mm.title
WHERE m.postcounter = 1
GROUP BY m.title, m.author