1

我有一个这样的 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

关于如何做到这一点的任何提示?

一切顺利,西蒙妮

4

2 回答 2

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;
于 2013-10-31T11:42:04.960 回答
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
于 2013-10-31T11:42:22.453 回答