views:

63

answers:

4

Hi,

here is the "msg" table on mysql

sent_to  customer   msg      read
-------  --------  ------   -----
45          3       bla       0
34          4        bla       1
34          6        bla       0
45          3        bla       0
56          7        bla       1
45          8        bla       0

for example user whose id number is 45 logs in,

i want him to see this,

you have 2 unread msg to your "number 3" customer
you have 1 unread msg to your "number 8" customer

like a news feed

what query should i use for this ?

thx

A: 

...

select count(*), customer from msg where read = 0 group by customer
El Guapo
and `sent_to` presumably?
Simon Nickerson
most definitely!
El Guapo
+1  A: 

You may want to use the following query.

SELECT   CONCAT('You have ', 
                COUNT(`read`), 
                ' unread msg to your number ', 
                customer, 
                ' customer') AS news
FROM     msg 
WHERE    `read` = '0' AND `sent_to` = '45'
GROUP BY customer;

Note that read is a reserved word in MySQL, so you have to enclose it in backticks. (Source)

Test case:

CREATE TABLE msg (
    `sent_to`    int,
    `customer`   int,
    `msg`        varchar(10),
    `read`       int
);

INSERT INTO msg VALUES(45, 3, 'bla', 0);
INSERT INTO msg VALUES(34, 4, 'bla', 1);
INSERT INTO msg VALUES(34, 6, 'bla', 0);
INSERT INTO msg VALUES(45, 3, 'bla', 0);
INSERT INTO msg VALUES(56, 7, 'bla', 1);
INSERT INTO msg VALUES(45, 8, 'bla', 0);

Query result:

+-------------------------------------------------+
| news                                            |
+-------------------------------------------------+
| You have 2 unread msg to your number 3 customer |
| You have 1 unread msg to your number 8 customer |
+-------------------------------------------------+
2 rows in set (0.00 sec)
Daniel Vassallo
thanks for great answer, and also giving info about "read", i have a problem, mysql_num_rows gives 0 even though i have "read = 0" in the database ?
Ahmet vardar
oh ok i fixed it thx
Ahmet vardar
+1  A: 
SELECT COUNT(read), customer FROM msg WHERE read = 0 AND sent_to = '45' GROUP BY customer;
+1  A: 
select count(sent_to), customer
from msg 
where read < 1
and sent_to = 45
group by customer
geeko