Reputation: 6805
I currently have a MySQL SELECT statement that pulls information from two tables to display a "Sent Messages" field for private messaging.
I'd like to know how I can do add a COUNT to my query to count the number of "receivers" in one thread.
Here's the basic gist of my table structure, (NOTE: the relational tie between the two tables is the 'message-id' in pm-info and the "id" in pm_data):
pm_info:
id message_id receiver_id is_read read_date
pm_data:
id date_sent title sender_id thread_id content
Here's my SELECT Statement:
SELECT pm_info.is_read, group_concat(DISTINCT receiver.usrFirst) as receiver_name,
pm_data.date_sent, pm_data.title, pm_data.thread_id, pm_data.id as data_id,
MAX(date_sent) AS thread_max_date_sent
FROM pm_info
INNER JOIN pm_data ON pm_info.message_id = pm_data.id
INNER JOIN tblUsers AS receiver ON pm_info.receiver_id = receiver.usrID
WHERE pm_data.sender_id = '$usrID'
GROUP BY pm_data.thread_id
ORDER BY thread_max_date_sent DESC
And it ouputs the recipients like this:
Message 1 - Recipients: John, David, Steve - thread_id = 1234
Message 2 - Recipients: Bill, David, John, Ed, Steve - thread_id = 1345
Basically, what I'd like to do is have the option to COUNT the recipients, so in the example above, "Message 1" would display three (3) recipients, and "Message 2" would display five (5) recipients.
This way, if I have a thread/message that was sent to 30 users, not all thirty names will be printed out.
Thanks!
Upvotes: 0
Views: 7163
Reputation: 6858
You could move the count and group_concat into a concat statement.
... group_concat(DISTINCT receiver.usrFirst) as receiver_name ...
becomes
... concat('messages:', count(distinct receiver.usrFirst),'(',group_concat(DISTINCT receiver.usrFirst),')') as receiver_name ...
Upvotes: 0
Reputation: 536
Have you tried just replacing GROUP_CONCAT with COUNT? Like this:
COUNT(DISTINCT receiver.usrFirst) as receiver_count
Or better, use pm_info.receiver_id as in (which could potentially let you eliminate one of your joins):
COUNT(DISTINCT pm_info.receiver_id) as receiver_count
Upvotes: 2
Reputation: 238086
You could use a subquery to select up to 3 recipients per message, and then another subquery to concatenate their names:
select
( select group_concat(usrFirst separator ', ')
from tblUsers
where usrId in (
select usrId
from tblUsers
where usrId = pm_info.receiver_id
limit 3
)
) as receiver_name
from pm_info
....
Upvotes: 0