Question

I have a MySQL table like this:

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

I want to take, for all the discussions, who is the starter of the discussion (which is author with postcounter = 1) and how many posts have been made in each discussion. I am trying to make two select and a UNION ALL to accomplish this:

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

So now I have:

THREAD     STARTER   POSTS
mythread   me        0
mythread   0         3

and I'd like to reduce the result to:

THREAD     STARTER   POSTS
mythread   me        3

Any hint on how to accomplish this?

All the Best, Simone

Was it helpful?

Solution

How about using a join back onto the table instead?

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

OTHER TIPS

You could join these queries by the title:

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top