Conditional counting with group in section where

I have a simple messaging system - keeping all messages in one table. Each post can (and should) be linked to one of three other tables that represent some sections of the website. Here is the create table statement

CREATE TABLE `messages` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `from_user_id` int(11) DEFAULT NULL,
  `to_user_id` int(11) DEFAULT NULL,
  `message` text COLLATE utf8_bin,
  `table1_id` int(11) DEFAULT NULL,
  `table2_id` int(11) DEFAULT NULL,
  `table3_id` int(11) DEFAULT NULL,
  `is_unread` tinyint(1) DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

      

For each message from table1_id, table2_id and table3_id

, if there is a value in some column, it means that the other 2 are zero. Here is the sqlfiddle structure and example data: http://sqlfiddle.com/#!9/b98a2/1/0 .

So there table1_id, table2_id and table3_id

are several threads that I use when grouping to display a list of posts. Here is my request

SELECT 
  id,
  table1_id,
  table2_id,
  table3_id,
  message,
  from_user_id,
  to_user_id,
  COUNT(table1_id) AS t1_count,
  COUNT(table2_id) AS t2_count,
  COUNT(table3_id) AS t3_count,
  MAX(CASE WHEN to_user_id = 10 AND is_unread = 1 THEN 1 END) AS is_unread,
  COUNT(CASE WHEN to_user_id = 10 THEN 1 END) AS inbox_count
FROM
  messages
WHERE to_user_id = 10 OR from_user_id = 10
GROUP BY table1_id,
  table2_id,
  table3_id
ORDER BY id DESC

      

and this is in the sqlfiddle http://sqlfiddle.com/#!9/b98a2/2/0

This query works fine when I have to show all messages, but if, for example, I only want to show the user's mailbox with id = 10

I need to check the condition that there is at least one received message for each thread, so for that I tried to apply the condition AND inbox_count > 0

. resulting in an error Unknown column 'inbox_count' in 'where clause'

.

I'm trying to list messages similar to gmail - showing the total messages count ( t1_count, t2_count or t3_count

) for a stream, so I can't seem to remove the part OR from_user_id = 10

.

Why can't it find this column and how can I apply this condition to display a list of received (outgoing) messages.

+3


source to share


1 answer


If I completely misunderstand your intent ... If you want to filter with using inbox_count > 0

then I think you want to add

HAVING COUNT(CASE WHEN to_user_id = 10 THEN 1 END) > 0

      



after the offer group by

. This will remove "threads" that have no message from to_user = 10

.

See this fiddle and example.

+2


source







All Articles